This course is to give the understanding of open data, open science, and open research tools.
I am feeling confused and a bit stressed. But also excited as well.
My expectations are:
Then just a couple of lists to learn to make the lists:
I heard from this course from my colleague.
Here is the link to my github repository https://github.com/tiinasip/IODS-project
And here is the link to my diary https://tiinasip.github.io/IODS-project/
Another way to add the link to my diary
Work summary I have went through Data camp parts R short and sweet and Regression and model validation. I have also listened a couple of statistics classes from YouTube and went through the chapters 3 & 4 from Kimmo’s textbook.
I have learned some basics in R and refreshed my knowledge about regression analysis.
Code for data creation is available at https://github.com/tiinasip/IODS-project/blob/master/data/create_learning2014.R
Code for data analysis (although it is thoroughly described in this report) https://github.com/tiinasip/IODS-project/blob/master/Exercise2_AnalysisPart.R
Data was collected in a survey for students attending statistics course. The aim was to find out, which factors have effect on course success. Originally there were many questions that were now grouped to be strategic, surface and deep questions.
Analysis starts with reading the data and taking the summary:
learnings2 <- read.table("http://s3.amazonaws.com/assets.datacamp.com/production/course_2218/datasets/learning2014.txt ", sep=",", header=TRUE)
dim(learnings2)
str(learnings2)
summary(learnings2)
dim(learnings2)
## [1] 166 7
str(learnings2)
## 'data.frame': 166 obs. of 7 variables:
## $ gender : Factor w/ 2 levels "F","M": 1 2 1 2 2 1 2 1 2 1 ...
## $ age : int 53 55 49 53 49 38 50 37 37 42 ...
## $ attitude: num 3.7 3.1 2.5 3.5 3.7 3.8 3.5 2.9 3.8 2.1 ...
## $ deep : num 3.58 2.92 3.5 3.5 3.67 ...
## $ stra : num 3.38 2.75 3.62 3.12 3.62 ...
## $ surf : num 2.58 3.17 2.25 2.25 2.83 ...
## $ points : int 25 12 24 10 22 21 21 31 24 26 ...
summary(learnings2)
## gender age attitude deep stra
## F:110 Min. :17.00 Min. :1.400 Min. :1.583 Min. :1.250
## M: 56 1st Qu.:21.00 1st Qu.:2.600 1st Qu.:3.333 1st Qu.:2.625
## Median :22.00 Median :3.200 Median :3.667 Median :3.188
## Mean :25.51 Mean :3.143 Mean :3.680 Mean :3.121
## 3rd Qu.:27.00 3rd Qu.:3.700 3rd Qu.:4.083 3rd Qu.:3.625
## Max. :55.00 Max. :5.000 Max. :4.917 Max. :5.000
## surf points
## Min. :1.583 Min. : 7.00
## 1st Qu.:2.417 1st Qu.:19.00
## Median :2.833 Median :23.00
## Mean :2.787 Mean :22.72
## 3rd Qu.:3.167 3rd Qu.:27.75
## Max. :4.333 Max. :33.00
There are 166 rows and 7 variables/columns. 7 variables are: gender, age, attitude, deep, stra, surf and points. Gender is factor (male/female), age and points are integer, attiture, deep , stra and surf are numeric.
Medians and means seem to be quite close to each other, which is one indication of normal distribution but does not confirm it alone.
pairs(learnings2[-1],col = learnings2$gender, main="Graphical summary")
The scatter plot shows low correlations to other combinations thant points and attitude. For instance, stra and surf seem to have no correlations as the points are distributed widely. There is no clear positive, negative or curved correlation clearly visible in the figure.
Analysis is continued with a more detailed graphical analysis of variables. First without gender graphical summary.
library(GGally)
## Loading required package: ggplot2
## Registered S3 method overwritten by 'GGally':
## method from
## +.gg ggplot2
library(ggplot2)
ggpairs(learnings2, mapping = aes(), title="Scatter plot matrix, no gender as column ",lower = list(combo = wrap("facethist", bins = 20)))
And then by gender
# create a more advanced plot matrix with ggpairs()
ggpairs(learnings2, mapping = aes(col=gender, alpha = 0.3), title="Graphical summary and gender ",
lower = list(combo = wrap("facethist", bins = 20))
)
#Distributions Age distribution is right-tailed, deep is left-tailed, especially for males. Strategic distribution is approximately symmetrical, especially for males. Surface is also quite symmetric. Attitude is interesting. When both genders are in, it looks quite symmetric. But for males it is left-tailed Points are bimodally distributed or for males even multimodal. Gender is nominal measurement meaning the categories are mutually exclusive and have no logical order.
If the correlation is between +/- 0.5 and +/-1, the correlation could be strong. Only points and attitude correlation (0.437) is close to that, which indicates that they have the strongest connection in the data and other variables are not that meaningful. The second highest correlation is between surf and deep, but it is -0.324.
#Regression Three variables selected as explanatory are: - Attitude - Strategic - Surface They were selected, because they had highest absolute correlations (0,437,0,146 and 0,144) with the points, which is our target variable.
First the model with only attitude
qplot(attitude, points, data = learnings2) + geom_smooth(method = "lm")
my_model <- lm(points ~ attitude, data = learnings2)
summary(my_model)
##
## Call:
## lm(formula = points ~ attitude, data = learnings2)
##
## Residuals:
## Min 1Q Median 3Q Max
## -16.9763 -3.2119 0.4339 4.1534 10.6645
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 11.6372 1.8303 6.358 1.95e-09 ***
## attitude 3.5255 0.5674 6.214 4.12e-09 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 5.32 on 164 degrees of freedom
## Multiple R-squared: 0.1906, Adjusted R-squared: 0.1856
## F-statistic: 38.61 on 1 and 164 DF, p-value: 4.119e-09
my_model <- lm(points ~ attitude, data = learnings2)
results <- summary(my_model)
P values of both intercept and attitude are under 0.05 indicating significant statistic correlation. T value is >2 indicating that as well.
Validation of graphical model is below. Normal Q-Q shows that both attitude and points seem to come from the same distribution, forming a line that’s roughly straight. It seems that the variables are normally distributed, although some pairs both at the beginning and at the end are not following the line.
Residuals vs. fitted tests, if the relationship of the variables is linear. If the plot is relatively shapeless, there are no obvious outliers and the data is generally symmetrically around 0 line, it is indicating linearity. In this case the plot is quite good as there is no pattern. There are some outliers, but not many and the values are around 0.
plot(my_model, which=c(1,2,5))
Also residuals vs. leverage figure indicates that there are no significant outliers. There are no many points in outside Cook’s distance line meaning there are not outliers that would change the regression result if I exclude those cases.
Next step is to add stra to the model and check the summary.
my_model2 <- lm(points ~ attitude + stra, data = learnings2)
summary(my_model2)
##
## Call:
## lm(formula = points ~ attitude + stra, data = learnings2)
##
## Residuals:
## Min 1Q Median 3Q Max
## -17.6436 -3.3113 0.5575 3.7928 10.9295
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 8.9729 2.3959 3.745 0.00025 ***
## attitude 3.4658 0.5652 6.132 6.31e-09 ***
## stra 0.9137 0.5345 1.709 0.08927 .
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 5.289 on 163 degrees of freedom
## Multiple R-squared: 0.2048, Adjusted R-squared: 0.1951
## F-statistic: 20.99 on 2 and 163 DF, p-value: 7.734e-09
Third model is created by adding both stra and surf to the first model and check if the model is improved.
my_model3 <- lm(points ~ attitude + stra + surf, data = learnings2)
summary(my_model3)
##
## Call:
## lm(formula = points ~ attitude + stra + surf, data = learnings2)
##
## Residuals:
## Min 1Q Median 3Q Max
## -17.1550 -3.4346 0.5156 3.6401 10.8952
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 11.0171 3.6837 2.991 0.00322 **
## attitude 3.3952 0.5741 5.913 1.93e-08 ***
## stra 0.8531 0.5416 1.575 0.11716
## surf -0.5861 0.8014 -0.731 0.46563
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 5.296 on 162 degrees of freedom
## Multiple R-squared: 0.2074, Adjusted R-squared: 0.1927
## F-statistic: 14.13 on 3 and 162 DF, p-value: 3.156e-08
The second model with attitude and stra does not seem to create the model better. Stra’s p value is >0.05 meaning it is not statistically significant and could be dropped from the model.
The third model with attitude, stra and surf ends up to the same conclusion. Both stra and surf have p value >0.05 meaning they could be dropped from the model.It is adviced that one should choose the simple model when adding the variables does not improve the model.
But when the adjusted R-squares are checked, the situation changes. The adjusted R-squared compares the explanatory power of regression models that contain different numbers of predictors. Adjusted R-square of the model is 0.1856. The second model has adjusted R-square 0.1951. The third model has adjusted R-squared 0.1927. However, all these adjusted R values are low. Adjusted R-square tells the proportion of the variability in the dependent variable that is explained by the model.
I check still the diagnostics of model 2 regressio, but their output is very similar to the diagnostics of the first model.
plot(my_model2, which=c(1,2,5))
It is generally advisable to use simpler model when possible. As additional coefficients did not create clearly better model, I would use the simple points ~ attitude model.
Work summary
Code for data creation is available at https://github.com/tiinasip/IODS-project/blob/master/data/create_alc.R
Code for data analysis (although it is thoroughly described in this report) https://github.com/tiinasip/IODS-project/blob/master/data/alc_analysis.R
Data is about student achievent in seconday education of two Portuguese schools.The data attributes include student grades, demographic, social and school related features) and it was collected by using school reports and questionnaires. The purpose of the analysis to find relationships between high or low alcohol consumption and other variables available.
Analysis starts with reading the data and taking the summary:
alc <- read.table("http://s3.amazonaws.com/assets.datacamp.com/production/course_2218/datasets/alc.txt", sep=",", header=TRUE)
dim(alc)
str(alc)
summary(alc)
library(GGally)
library(ggplot2)
library(dplyr)
##
## Attaching package: 'dplyr'
## The following object is masked from 'package:GGally':
##
## nasa
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
library(tidyr)
gather(alc) %>% ggplot(aes(value)) + facet_wrap("key", scales = "free")+geom_bar()
## Warning: attributes are not identical across measure variables;
## they will be dropped
alc_gender <- ggplot(alc, aes(x = high_use, y = G3, col=sex))
alc_gender + geom_boxplot(outlier.colour="green") + ylab("grade")+ggtitle("Student grades by alcohol consumption and sex, outliers green")
There are some outliers, which are coloured green.Next check the crosstables between gender and high use.
alc_gender_table <-table(alc$sex,alc$high_use)
prop.table(alc_gender_table,2) #based on column totals
##
## FALSE TRUE
## F 0.5814815 0.3660714
## M 0.4185185 0.6339286
prop.table(alc_gender_table,1) #based on row totals
##
## FALSE TRUE
## F 0.7929293 0.2070707
## M 0.6141304 0.3858696
g1_ge <- ggplot(data = alc, aes(x = high_use, fill=sex))
g1_ge + geom_bar()+ggtitle("Gender and high alcohol use")
Gender in the data follows binomial distribution. 63 % of high users are males.Also the percentage of high users is higher for males (39%) than females (21%)
alc_higher <- ggplot(alc, aes(x = high_use, y = G3, col=higher))
alc_higher + geom_boxplot(outlier.colour="green") + ylab("grade")+ggtitle("Student grades by alcohol consumption and higher education")
alc_higher_table <-table(alc$higher,alc$high_use)
prop.table(alc_higher_table,2) #based on column totals
##
## FALSE TRUE
## no 0.03333333 0.08035714
## yes 0.96666667 0.91964286
prop.table(alc_higher_table,1) #based on row totals
##
## FALSE TRUE
## no 0.500000 0.500000
## yes 0.717033 0.282967
g1_hi <- ggplot(data = alc, aes(x = high_use, fill=higher))
g1_hi + geom_bar()+ggtitle("Higher education target and high alcohol use")
Higher education target follows binomial distribution.8 % of high users are not targetting higher indicating that higher education target may not explain much of high use. Also the percentage of high use is only 50 % for students not targeting higher education.
alc_romantic <- ggplot(alc, aes(x = high_use, y = G3, col=romantic))
alc_romantic + geom_boxplot(outlier.colour="green") + ylab("grade")+ggtitle("Student grades by alcohol consumption and romantic relationship")
alc_romantic_table <-table(alc$romantic,alc$high_use)
prop.table(alc_romantic_table,2) #based on column totals
##
## FALSE TRUE
## no 0.6740741 0.7053571
## yes 0.3259259 0.2946429
prop.table(alc_romantic_table,1) #based on row totals
##
## FALSE TRUE
## no 0.6973180 0.3026820
## yes 0.7272727 0.2727273
g1_ro <- ggplot(data = alc, aes(x = high_use, fill=romantic))
g1_ro + geom_bar()+ggtitle("Romantic relationship and high alcohol use")
Romantic relationship ollows binomial distribution.71 % of high users are not in romantic relationship. However, the share of high user from students having romantic relationship is 27% and from students not having relationship 30%. It seems that romantic relationship may not explain much.
alc$studytime <-as.factor(alc$studytime)
alc_studytime <- ggplot(alc, aes(x = studytime, y = G3, col=high_use))
alc_studytime + geom_boxplot(outlier.colour="red") + ylab("grade")+ggtitle("Student grades by alcohol consumption and weekly studytime")
alc_studytime_table <-table(alc$studytime,alc$high_use)
prop.table(alc_studytime_table,2) #based on column totals
##
## FALSE TRUE
## 1 0.22222222 0.38392857
## 2 0.49259259 0.50892857
## 3 0.20000000 0.07142857
## 4 0.08518519 0.03571429
prop.table(alc_studytime_table,1) #based on row totals
##
## FALSE TRUE
## 1 0.5825243 0.4174757
## 2 0.7000000 0.3000000
## 3 0.8709677 0.1290323
## 4 0.8518519 0.1481481
g1_st <- ggplot(data = alc, aes(x = studytime, fill=high_use))
g1_st + geom_bar()+ggtitle("Studytime and high alcohol use")
Studytime follows ordinal scale. The percentages of high users are highest in studytime groups 1 and 2 (38% and 51%, respectively). The share of high users in studytime group 1 is the highest (42%). Surprisingly, the highest median grade is among high users whose study a lot. But for non-high-users the highest median is in the studytime group 3. However, n is much lower in studytime groups 3 and 4, so individiual performance influences more.
alc_activities <- ggplot(alc, aes(x = high_use, y = G3, col=activities))
alc_activities + geom_boxplot(outlier.colour="green") + ylab("grade")+ggtitle("Student grades by alcohol consumption and activities")
alc_activities_table <-table(alc$activities,alc$high_use)
prop.table(alc_activities_table,2) #based on column totals
##
## FALSE TRUE
## no 0.4518519 0.5267857
## yes 0.5481481 0.4732143
prop.table(alc_activities_table,1) #based on row totals
##
## FALSE TRUE
## no 0.6740331 0.3259669
## yes 0.7363184 0.2636816
g1_ac <- ggplot(data = alc, aes(x = high_use, fill=activities))
g1_ac + geom_bar()+ggtitle("Activities and high alcohol use")
Activities follow binomial distribution.53 % of high users are not doing activities. However, the share of high user from students having activities is 27% and from students not having activites 33%. It seems that activities may not explain much.
As a conclusion it seems that my chosen variables are not explaining much. Sex and studytime seem to be the srongest candidates. Next I create model.
# find the model with glm()
m <- glm(high_use ~ sex + higher+ romantic + activities + studytime, data = alc, family = "binomial")
summary(m)
##
## Call:
## glm(formula = high_use ~ sex + higher + romantic + activities +
## studytime, family = "binomial", data = alc)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -1.2851 -0.8818 -0.6724 1.2023 2.1803
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -0.36148 0.56212 -0.643 0.52018
## sexM 0.68577 0.25344 2.706 0.00681 **
## higheryes -0.38258 0.51758 -0.739 0.45980
## romanticyes -0.07465 0.26167 -0.285 0.77541
## activitiesyes -0.30089 0.24016 -1.253 0.21025
## studytime2 -0.25227 0.27284 -0.925 0.35517
## studytime3 -1.15983 0.45238 -2.564 0.01035 *
## studytime4 -1.10844 0.59105 -1.875 0.06074 .
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 462.21 on 381 degrees of freedom
## Residual deviance: 432.87 on 374 degrees of freedom
## AIC: 448.87
##
## Number of Fisher Scoring iterations: 4
#coefficients
coef(m)
## (Intercept) sexM higheryes romanticyes activitiesyes
## -0.36148480 0.68577438 -0.38258312 -0.07465366 -0.30089256
## studytime2 studytime3 studytime4
## -0.25227181 -1.15983304 -1.10843894
From model it is clear that only sex and studytime are significant in the model. For others Pr(>|z|) is more than 0.05. I had five hypothesis and two of them were true in the sample indicating that there is a relationship in the population. Other 3 hypothesis were rejected based on the sample.
Odds ratio greater than one means odds are getting larger. Only sex is more than one so it is increasing odds that the student is a high-user. Odds ratio less than one means odds are getting smaller. Studytime has the smallest odds ratio. Confidence interval of studytime is (0.47, 0.87) meaning it remains under 1. Respectively sex’s confidence interval remains clearly over 1 (1.21, 3.25). On the other hand, non-meaningful variables have confidence intervals having values below and above 1 indicating that odds ratio is not significant for decision making.
# compute odds ratios (OR)
OR <- coef(m) %>% exp
# compute confidence intervals (CI)
CI <-confint(m)%>% exp
## Waiting for profiling to be done...
# print out the odds ratios with their confidence intervals
cbind(OR, CI)
## OR 2.5 % 97.5 %
## (Intercept) 0.6966412 0.22877627 2.1168399
## sexM 1.9853086 1.21136731 3.2780894
## higheryes 0.6820972 0.24452974 1.9096568
## romanticyes 0.9280649 0.55145455 1.5424153
## activitiesyes 0.7401573 0.46121490 1.1844172
## studytime2 0.7770335 0.45603512 1.3317371
## studytime3 0.3135385 0.12224825 0.7335040
## studytime4 0.3300738 0.09000723 0.9651789
As higher, romantic and activities were not significant, a new model is created and used for prediction as instructed.
m2 <- glm(high_use ~ sex + studytime, data = alc, family = "binomial")
summary(m2)
##
## Call:
## glm(formula = high_use ~ sex + studytime, family = "binomial",
## data = alc)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -1.1060 -0.8527 -0.7405 1.2506 2.1042
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -0.8246 0.2763 -2.985 0.00284 **
## sexM 0.6543 0.2460 2.659 0.00783 **
## studytime2 -0.3292 0.2658 -1.239 0.21540
## studytime3 -1.2735 0.4439 -2.869 0.00412 **
## studytime4 -1.2025 0.5858 -2.053 0.04010 *
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 462.21 on 381 degrees of freedom
## Residual deviance: 435.28 on 377 degrees of freedom
## AIC: 445.28
##
## Number of Fisher Scoring iterations: 4
#coefficients
coef(m2)
## (Intercept) sexM studytime2 studytime3 studytime4
## -0.8246325 0.6542694 -0.3292488 -1.2735443 -1.2025286
Odds ratios and confidence intervals of new model.
# compute odds ratios (OR)
OR <- coef(m2) %>% exp
# compute confidence intervals (CI)
CI <-confint(m2)%>% exp
## Waiting for profiling to be done...
# print out the odds ratios with their confidence intervals
cbind(OR, CI)
## OR 2.5 % 97.5 %
## (Intercept) 0.4383961 0.25246554 0.7477169
## sexM 1.9237365 1.19050659 3.1290488
## studytime2 0.7194640 0.42763809 1.2143282
## studytime3 0.2798380 0.11064760 0.6421976
## studytime4 0.3004336 0.08256457 0.8676192
# predict() the probability of high_use
probabilities <- predict(m2, type = "response")
# add the predicted probabilities to 'alc'
alc <- mutate(alc, probability = probabilities)
# use the probabilities to make a prediction of high_use
alc <- mutate(alc, prediction = probability>0.5)
# see the last ten original classes, predicted probabilities, and class predictions
select(alc, sex, studytime, high_use, probability, prediction) %>% tail(10)
## sex studytime high_use probability prediction
## 373 M 1 FALSE 0.4575119 FALSE
## 374 M 1 TRUE 0.4575119 FALSE
## 375 F 3 FALSE 0.1092742 FALSE
## 376 F 1 FALSE 0.3047812 FALSE
## 377 F 3 FALSE 0.1092742 FALSE
## 378 F 2 FALSE 0.2397809 FALSE
## 379 F 2 FALSE 0.2397809 FALSE
## 380 F 2 FALSE 0.2397809 FALSE
## 381 M 1 TRUE 0.4575119 FALSE
## 382 M 1 TRUE 0.4575119 FALSE
Binary predictions in figure:
#a plot of 'high_use' versus 'probability' in 'alc'
g <- ggplot(alc, aes(x = probability, y = high_use, col=prediction))
g+geom_point(aes(col=prediction))
The model predict correctly in 270 cases of non-users. But the model did not predict any high-users at all. The same prediction power is just always guess that the student is not a high-user, and it is actually a relevant idea compared to the bad model, because 71 % of students in the survey were not high-users.
# tabulate the target variable versus the predictions
table(high_use = alc$high_use, prediction = alc$prediction)
## prediction
## high_use FALSE
## FALSE 270
## TRUE 112
table(high_use = alc$high_use, prediction = alc$prediction) %>% prop.table() %>% addmargins()
## prediction
## high_use FALSE Sum
## FALSE 0.7068063 0.7068063
## TRUE 0.2931937 0.2931937
## Sum 1.0000000 1.0000000
Analysis by models have advantages over guessing. In this case guessing produced good candidates, but the analysis showed their weaknesses. On the other hand, there were probably many other variables which had had significance but I did not take them into analysis because of my prejudices.
Work summary
Codes are available at
Boston dataset contains information collected by the U.S Census Service concerning housing valuesin the area of Boston Mass. It was obtained from the StatLib archive. More information about each variable can be found in here
Descriptions of variables are:
library(MASS)
data("Boston")
dim(Boston)
## [1] 506 14
str(Boston)
## 'data.frame': 506 obs. of 14 variables:
## $ crim : num 0.00632 0.02731 0.02729 0.03237 0.06905 ...
## $ zn : num 18 0 0 0 0 0 12.5 12.5 12.5 12.5 ...
## $ indus : num 2.31 7.07 7.07 2.18 2.18 2.18 7.87 7.87 7.87 7.87 ...
## $ chas : int 0 0 0 0 0 0 0 0 0 0 ...
## $ nox : num 0.538 0.469 0.469 0.458 0.458 0.458 0.524 0.524 0.524 0.524 ...
## $ rm : num 6.58 6.42 7.18 7 7.15 ...
## $ age : num 65.2 78.9 61.1 45.8 54.2 58.7 66.6 96.1 100 85.9 ...
## $ dis : num 4.09 4.97 4.97 6.06 6.06 ...
## $ rad : int 1 2 2 3 3 3 5 5 5 5 ...
## $ tax : num 296 242 242 222 222 222 311 311 311 311 ...
## $ ptratio: num 15.3 17.8 17.8 18.7 18.7 18.7 15.2 15.2 15.2 15.2 ...
## $ black : num 397 397 393 395 397 ...
## $ lstat : num 4.98 9.14 4.03 2.94 5.33 ...
## $ medv : num 24 21.6 34.7 33.4 36.2 28.7 22.9 27.1 16.5 18.9 ...
summary(Boston)
## crim zn indus chas
## Min. : 0.00632 Min. : 0.00 Min. : 0.46 Min. :0.00000
## 1st Qu.: 0.08204 1st Qu.: 0.00 1st Qu.: 5.19 1st Qu.:0.00000
## Median : 0.25651 Median : 0.00 Median : 9.69 Median :0.00000
## Mean : 3.61352 Mean : 11.36 Mean :11.14 Mean :0.06917
## 3rd Qu.: 3.67708 3rd Qu.: 12.50 3rd Qu.:18.10 3rd Qu.:0.00000
## Max. :88.97620 Max. :100.00 Max. :27.74 Max. :1.00000
## nox rm age dis
## Min. :0.3850 Min. :3.561 Min. : 2.90 Min. : 1.130
## 1st Qu.:0.4490 1st Qu.:5.886 1st Qu.: 45.02 1st Qu.: 2.100
## Median :0.5380 Median :6.208 Median : 77.50 Median : 3.207
## Mean :0.5547 Mean :6.285 Mean : 68.57 Mean : 3.795
## 3rd Qu.:0.6240 3rd Qu.:6.623 3rd Qu.: 94.08 3rd Qu.: 5.188
## Max. :0.8710 Max. :8.780 Max. :100.00 Max. :12.127
## rad tax ptratio black
## Min. : 1.000 Min. :187.0 Min. :12.60 Min. : 0.32
## 1st Qu.: 4.000 1st Qu.:279.0 1st Qu.:17.40 1st Qu.:375.38
## Median : 5.000 Median :330.0 Median :19.05 Median :391.44
## Mean : 9.549 Mean :408.2 Mean :18.46 Mean :356.67
## 3rd Qu.:24.000 3rd Qu.:666.0 3rd Qu.:20.20 3rd Qu.:396.23
## Max. :24.000 Max. :711.0 Max. :22.00 Max. :396.90
## lstat medv
## Min. : 1.73 Min. : 5.00
## 1st Qu.: 6.95 1st Qu.:17.02
## Median :11.36 Median :21.20
## Mean :12.65 Mean :22.53
## 3rd Qu.:16.95 3rd Qu.:25.00
## Max. :37.97 Max. :50.00
According to the information the Boston data frame has 506 rows and 14 columns. That is equal to my check. All variables are either numeric or int. There is no missing values either:
sum(is.na(Boston))
## [1] 0
mean(is.na(Boston))
## [1] 0
From graphical overview it is easy to notice at least the following:
library(GGally)
library(ggplot2)
ggpairs(Boston, title=“Scatter plot matrix, distributions”,lower = list( continuous = “smooth”,mapping = aes()))
Scatter plot matrix
pairs(Boston[-1], main="Graphical summary")
Scaling targets to normalising:
boston_scaled <- scale(Boston)
summary(boston_scaled)
## crim zn indus
## Min. :-0.419367 Min. :-0.48724 Min. :-1.5563
## 1st Qu.:-0.410563 1st Qu.:-0.48724 1st Qu.:-0.8668
## Median :-0.390280 Median :-0.48724 Median :-0.2109
## Mean : 0.000000 Mean : 0.00000 Mean : 0.0000
## 3rd Qu.: 0.007389 3rd Qu.: 0.04872 3rd Qu.: 1.0150
## Max. : 9.924110 Max. : 3.80047 Max. : 2.4202
## chas nox rm age
## Min. :-0.2723 Min. :-1.4644 Min. :-3.8764 Min. :-2.3331
## 1st Qu.:-0.2723 1st Qu.:-0.9121 1st Qu.:-0.5681 1st Qu.:-0.8366
## Median :-0.2723 Median :-0.1441 Median :-0.1084 Median : 0.3171
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.:-0.2723 3rd Qu.: 0.5981 3rd Qu.: 0.4823 3rd Qu.: 0.9059
## Max. : 3.6648 Max. : 2.7296 Max. : 3.5515 Max. : 1.1164
## dis rad tax ptratio
## Min. :-1.2658 Min. :-0.9819 Min. :-1.3127 Min. :-2.7047
## 1st Qu.:-0.8049 1st Qu.:-0.6373 1st Qu.:-0.7668 1st Qu.:-0.4876
## Median :-0.2790 Median :-0.5225 Median :-0.4642 Median : 0.2746
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.6617 3rd Qu.: 1.6596 3rd Qu.: 1.5294 3rd Qu.: 0.8058
## Max. : 3.9566 Max. : 1.6596 Max. : 1.7964 Max. : 1.6372
## black lstat medv
## Min. :-3.9033 Min. :-1.5296 Min. :-1.9063
## 1st Qu.: 0.2049 1st Qu.:-0.7986 1st Qu.:-0.5989
## Median : 0.3808 Median :-0.1811 Median :-0.1449
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.4332 3rd Qu.: 0.6024 3rd Qu.: 0.2683
## Max. : 0.4406 Max. : 3.5453 Max. : 2.9865
When summary of scaled data is compared to the summary of the original data, it is obvious that magnitudes of min and max values have decreased and mean is always 0. For instance, max of lstat was 37.97 and after scaling 3.54, respectively black max 396.9 and 0.44. Zn min was 0, now -0.49, rm min was 3.56, now -3.88.
Next, categorial variable crim and its quantiles are calculated:
# change the object to data frame, because vector otherwise causes an error in next phase
boston_scaled<-as.data.frame(boston_scaled)
bins <- quantile(boston_scaled$crim)
bins
## 0% 25% 50% 75% 100%
## -0.419366929 -0.410563278 -0.390280295 0.007389247 9.924109610
crime <- cut(boston_scaled$crim, breaks = bins, include.lowest = TRUE, labels = c("low", "med_low", "med_high", "high"))
table(crime)
## crime
## low med_low med_high high
## 127 126 126 127
# remove original crim from the dataset
boston_scaled <- dplyr::select(boston_scaled, -crim)
# add the new categorical value to scaled data
boston_scaled <- data.frame(boston_scaled, crime)
Testing and training sets are created:
# number of rows in the Boston dataset
n <- nrow(boston_scaled)
# randomly 80% of the rows
ind <- sample(n, size = n * 0.8)
# creating train set
train <- boston_scaled[ind,]
# create testing set
test <- boston_scaled[-ind,]
# save the correct classes from test data
correct_classes <- test$crime
# remove the crime variable from test data
test <- dplyr::select(test, -crime)
Classification method LDA is used to findthe variables that separate the classes best and predict the classes of new data. In order to work, the variables should be normally distributed and each variable should have the same variance. Therefore scaled boston data is used. LDA model is created below and Crime is the target variable.
lda.fit <- lda(crime~., data = train)
lda.fit
## Call:
## lda(crime ~ ., data = train)
##
## Prior probabilities of groups:
## low med_low med_high high
## 0.2524752 0.2524752 0.2500000 0.2450495
##
## Group means:
## zn indus chas nox rm
## low 1.0185040 -0.9478753 -0.15653200 -0.8872605 0.41852336
## med_low -0.1055496 -0.2758982 -0.04073494 -0.5676199 -0.20038118
## med_high -0.4006369 0.2675949 0.23442641 0.4074627 0.02044586
## high -0.4872402 1.0149946 -0.11325431 1.0605218 -0.45450280
## age dis rad tax ptratio
## low -0.8797904 0.9536811 -0.7037620 -0.7106824 -0.4698956
## med_low -0.2979746 0.3725270 -0.5359958 -0.4838167 -0.1085225
## med_high 0.3876614 -0.3781538 -0.3848958 -0.2613023 -0.2817572
## high 0.8001417 -0.8329843 1.6596029 1.5294129 0.8057784
## black lstat medv
## low 0.37974977 -0.77077360 0.47452464
## med_low 0.31862377 -0.07272557 -0.03693218
## med_high 0.05246441 0.08604624 0.10763888
## high -0.72700043 0.86713863 -0.74765280
##
## Coefficients of linear discriminants:
## LD1 LD2 LD3
## zn 0.080858789 0.766131310 -0.85655787
## indus 0.018350250 -0.431692722 0.35369040
## chas -0.100168511 -0.096329231 0.01683003
## nox 0.258476536 -0.595441655 -1.48919612
## rm -0.105740451 -0.076724796 -0.23280236
## age 0.280169858 -0.126966613 -0.08692839
## dis -0.113449642 -0.242343375 0.14631937
## rad 3.240328112 0.873680981 0.29379235
## tax 0.006895238 0.031428910 0.21225040
## ptratio 0.101433846 0.048483851 -0.31384138
## black -0.155323170 0.006619192 0.08513014
## lstat 0.202467729 -0.346677828 0.30519091
## medv 0.152388585 -0.444479567 -0.24123350
##
## Proportion of trace:
## LD1 LD2 LD3
## 0.9469 0.0394 0.0136
# the function for lda biplot arrows
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "red", tex = 0.75, choices = c(1,2)){
heads <- coef(x)
arrows(x0 = 0, y0 = 0,
x1 = myscale * heads[,choices[1]],
y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
text(myscale * heads[,choices], labels = row.names(heads),
cex = tex, col=color, pos=3)
}
# target classes as numeric
classes <- as.numeric(train$crime)
Prior probabilities tell how training observations fell to crime categories. All probabilities are around 25 %. Group means show the mean value of each group by each variable. Coefficients of linear discriminants provides the linear combinations that are used to form the LDA decision rule. For instance, 0.131033364 * zn + 0.047138924 * indus ….0.237478243 * medv is the rule for LD1. Index of accessibility to radial highways (rad) has the largest coefficient value meaning it contibutes most. Average number of rooms per dwelling (rm) has the smallest coefficient; bigger houses with more rooms tend to locate on areas of low crime rates.Fit between proportion of trace fit between group variants
Proportion of trace is the percentage separation that each of the discriminant achieves. LD1 achieves already 95 %, when LD2 and LD 3 have only 4 % and 1 %. This means that the first linear discrimination is already enough.
There is a LDA biplot below.The biplot visualizes how variable rad contributes a lot in LD1 and it is contributing a lot also in LD2. Variable nox contributes in LD1 positively and in LD2 negatively, which was also seen from coefficients. Zn contributes in LD2, but not much in LD1. Other variables are around zero and do not stand out.
# plot the lda results
plot(lda.fit, dimen = 2, col=classes, pch=classes)
lda.arrows(lda.fit, myscale = 1)
lda.pred <- predict(lda.fit, newdata = test)
Next correct classes are saved and categorical variable is removed: correct_classes <- test$crime test <- dplyr::select(test, -crime)
Crime categories are cross tabulated by correct and predicted values. High values are well predicted. Lowest values were well predicted as well. Low med and high med categories have more incorrect predictions, but also for them most predictions went right.
# cross tabulate the results
table(correct = correct_classes, predicted = lda.pred$class)
## predicted
## correct low med_low med_high high
## low 15 9 1 0
## med_low 6 13 5 0
## med_high 0 10 15 0
## high 0 0 1 27
Boston dataset is reloaded again and the done modifications are not valid any more. Data is standardized by using scale function. Scaling was successfull, means are 0.
library(MASS)
data("Boston")
boston_scaled2 <- scale(Boston)
summary(boston_scaled2)
## crim zn indus
## Min. :-0.419367 Min. :-0.48724 Min. :-1.5563
## 1st Qu.:-0.410563 1st Qu.:-0.48724 1st Qu.:-0.8668
## Median :-0.390280 Median :-0.48724 Median :-0.2109
## Mean : 0.000000 Mean : 0.00000 Mean : 0.0000
## 3rd Qu.: 0.007389 3rd Qu.: 0.04872 3rd Qu.: 1.0150
## Max. : 9.924110 Max. : 3.80047 Max. : 2.4202
## chas nox rm age
## Min. :-0.2723 Min. :-1.4644 Min. :-3.8764 Min. :-2.3331
## 1st Qu.:-0.2723 1st Qu.:-0.9121 1st Qu.:-0.5681 1st Qu.:-0.8366
## Median :-0.2723 Median :-0.1441 Median :-0.1084 Median : 0.3171
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.:-0.2723 3rd Qu.: 0.5981 3rd Qu.: 0.4823 3rd Qu.: 0.9059
## Max. : 3.6648 Max. : 2.7296 Max. : 3.5515 Max. : 1.1164
## dis rad tax ptratio
## Min. :-1.2658 Min. :-0.9819 Min. :-1.3127 Min. :-2.7047
## 1st Qu.:-0.8049 1st Qu.:-0.6373 1st Qu.:-0.7668 1st Qu.:-0.4876
## Median :-0.2790 Median :-0.5225 Median :-0.4642 Median : 0.2746
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.6617 3rd Qu.: 1.6596 3rd Qu.: 1.5294 3rd Qu.: 0.8058
## Max. : 3.9566 Max. : 1.6596 Max. : 1.7964 Max. : 1.6372
## black lstat medv
## Min. :-3.9033 Min. :-1.5296 Min. :-1.9063
## 1st Qu.: 0.2049 1st Qu.:-0.7986 1st Qu.:-0.5989
## Median : 0.3808 Median :-0.1811 Median :-0.1449
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.4332 3rd Qu.: 0.6024 3rd Qu.: 0.2683
## Max. : 0.4406 Max. : 3.5453 Max. : 2.9865
class(boston_scaled2)
## [1] "matrix"
boston_scaled2<-as.data.frame(boston_scaled2)
Distances calculation:
dist_eu<- dist(boston_scaled2)
summary(dist_eu)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 0.1343 3.4625 4.8241 4.9111 6.1863 14.3970
Kmeans clustering and pairs are calculated, but the number of centers here is 4, which is just a guess what could be the optimal number.
km4 <-kmeans(boston_scaled2, centers = 4)
pairs(boston_scaled2, col = km4$cluster)
str(km4)
## List of 9
## $ cluster : Named int [1:506] 4 1 4 4 4 1 1 1 1 1 ...
## ..- attr(*, "names")= chr [1:506] "1" "2" "3" "4" ...
## $ centers : num [1:4, 1:14] -0.379 6.045 0.52 -0.399 -0.357 ...
## ..- attr(*, "dimnames")=List of 2
## .. ..$ : chr [1:4] "1" "2" "3" "4"
## .. ..$ : chr [1:14] "crim" "zn" "indus" "chas" ...
## $ totss : num 7070
## $ withinss : num [1:4] 1099.9 83.4 1417 1021.4
## $ tot.withinss: num 3622
## $ betweenss : num 3448
## $ size : int [1:4] 214 8 159 125
## $ iter : int 2
## $ ifault : int 0
## - attr(*, "class")= chr "kmeans"
km4
## K-means clustering with 4 clusters of sizes 214, 8, 159, 125
##
## Cluster means:
## crim zn indus chas nox rm
## 1 -0.3793188 -0.3566052 -0.3052421 0.003635902 -0.3800270 -0.2364042
## 2 6.0446656 -0.4872402 1.0149946 -0.272329068 1.0360489 -0.7484651
## 3 0.5200512 -0.4872402 1.1295348 0.024810573 1.1333512 -0.4374379
## 4 -0.3989700 1.2614609 -0.9791535 -0.020354653 -0.8573235 1.0090468
## age dis rad tax ptratio black
## 1 -0.06464777 0.1114978 -0.5852744 -0.6022621 0.0006816564 0.2791129
## 2 0.92099991 -1.0498086 1.6596029 1.5294129 0.8057784291 -1.6690729
## 3 0.79641518 -0.8439215 1.1655454 1.2611407 0.5893510622 -0.5709567
## 4 -0.96130713 0.9497716 -0.5867985 -0.6709807 -0.8023913663 0.3552363
## lstat medv
## 1 -0.1054488 -0.09593662
## 2 1.3857445 -1.49044810
## 3 0.8246602 -0.63447385
## 4 -0.9571271 1.06668290
##
## Clustering vector:
## 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
## 4 1 4 4 4 1 1 1 1 1 1 1 1 1 1 1 1 1
## 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
## 1 1 1 4 4 4 1 1 1 1 1 1 1 1 1 1 4 4
## 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
## 4 4 4 4 4 1 1 1 1 4 4 4 4 1 1 1 1 1
## 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
## 1 1 1 1 1 1 1 1 4 1 4 1 1 1 1 1 1 1
## 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
## 1 1 1 1 1 1 1 4 4 4 1 1 1 1 1 1 1 1
## 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
## 1 3 3 3 3 3 1 3 3 3 3 3 3 3 3 3 3 3
## 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
## 3 3 3 3 3 3 3 3 3 3 3 3 3 1 1 3 1 4
## 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
## 4 4 1 1 4 1 1 1 1 1 1 1 1 1 1 1 1 4
## 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
## 4 1 1 1 1 1 4 4 4 4 4 4 4 4 4 4 4 4
## 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
## 4 4 4 4 4 4 4 1 1 1 1 1 1 1 1 1 1 1
## 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
## 1 1 1 1 1 1 1 1 4 4 4 1 4 4 1 1 4 4
## 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
## 1 1 1 4 4 4 4 1 4 4 1 1 4 1 4 4 4 4
## 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
## 4 4 4 4 4 4 4 1 4 4 4 4 4 1 1 4 4 1
## 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
## 1 4 1 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4
## 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
## 4 4 4 4 4 1 1 4 1 1 4 4 4 4 4 4 4 4
## 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
## 4 4 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
## 1 1 1 1 1 1 1 1 4 1 1 1 1 1 1 1 1 4
## 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
## 1 4 4 1 1 4 4 4 4 4 4 4 4 4 3 3 3 3
## 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
## 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
## 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
## 3 3 2 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
## 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
## 3 3 2 3 3 3 3 3 2 2 3 3 3 3 2 3 3 3
## 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
## 2 3 3 3 2 3 3 3 3 3 3 3 3 2 3 3 3 3
## 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
## 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
## 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
## 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
## 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
## 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
## 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
## 3 3 3 3 3 3 3 1 1 1 1 1 1 1 1 1 1 1
## 505 506
## 1 1
##
## Within cluster sum of squares by cluster:
## [1] 1099.87756 83.38049 1416.96436 1021.42280
## (between_SS / total_SS = 48.8 %)
##
## Available components:
##
## [1] "cluster" "centers" "totss" "withinss"
## [5] "tot.withinss" "betweenss" "size" "iter"
## [9] "ifault"
Finding the optimal number of clusters is not irrelevant question and the textbook recommends the method to plot within-group sum of squares associated with the k-means solution for each number of groups. Then the “elbow” in the picture gives indication of the most useful solution. The plot below indicates that the elbow is in 2, after 2 the decrease is slower. However, even with 3 it is still significant but I choose to use 2.
set.seed(123)
# determine the number of clusters
k_max <- 10
# calculate the total within sum of squares
twcss <- sapply(1:k_max, function(k){kmeans(boston_scaled2, k)$tot.withinss})
# visualize the results
qplot(x = 1:k_max, y = twcss, geom = 'line', main="WGSS and groups in K-means solution")
Only 51 % total variance in data set that is explained by the first clustering with 4 clusters, which is not impressive. I checked how many clusters I should have to gain 80 % of total variance and it was 20. It is clear that it is too much, so I still keep 2 clusters, although the biggest decrease of variation ends at 2. In real-life I should check the correct number of clusters also by other methods, e.g. silhouette.
km <-kmeans(boston_scaled2, centers = 2)
pairs(boston_scaled2, col = km$cluster)
Cluster visualization with 2 clusters is clearer than the first guess of 4.
str(km)
## List of 9
## $ cluster : Named int [1:506] 1 1 1 1 1 1 1 1 1 1 ...
## ..- attr(*, "names")= chr [1:506] "1" "2" "3" "4" ...
## $ centers : num [1:2, 1:14] -0.389 0.724 0.262 -0.487 -0.615 ...
## ..- attr(*, "dimnames")=List of 2
## .. ..$ : chr [1:2] "1" "2"
## .. ..$ : chr [1:14] "crim" "zn" "indus" "chas" ...
## $ totss : num 7070
## $ withinss : num [1:2] 2686 1891
## $ tot.withinss: num 4577
## $ betweenss : num 2493
## $ size : int [1:2] 329 177
## $ iter : int 1
## $ ifault : int 0
## - attr(*, "class")= chr "kmeans"
km
## K-means clustering with 2 clusters of sizes 329, 177
##
## Cluster means:
## crim zn indus chas nox rm
## 1 -0.3894158 0.2621323 -0.6146857 0.002908943 -0.5823397 0.2446705
## 2 0.7238295 -0.4872402 1.1425514 -0.005407018 1.0824279 -0.4547830
## age dis rad tax ptratio black
## 1 -0.4331555 0.4540421 -0.5828749 -0.6291043 -0.2943707 0.3282754
## 2 0.8051309 -0.8439539 1.0834228 1.1693521 0.5471636 -0.6101842
## lstat medv
## 1 -0.4530491 0.3532917
## 2 0.8421083 -0.6566834
##
## Clustering vector:
## 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 1 1 1
## 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 1
## 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
## 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
## 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
## 2 2 2 2 2 2 2 2 2 2 2 2 2 1 1 2 1 1
## 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
## 1 1 1 2 1 2 1 1 2 2 1 1 1 1 1 1 1 1
## 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2
## 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
## 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
## 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
## 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
## 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
## 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
## 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
## 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
## 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
## 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
## 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
## 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
## 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
## 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
## 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
## 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 1
## 505 506
## 1 1
##
## Within cluster sum of squares by cluster:
## [1] 2686.045 1890.637
## (between_SS / total_SS = 35.3 %)
##
## Available components:
##
## [1] "cluster" "centers" "totss" "withinss"
## [5] "tot.withinss" "betweenss" "size" "iter"
## [9] "ifault"
The plot picture shows the groups are not equal size, one is 177 and other 329. There are some pairs, in which the grouping seems to work nicely; for instance medvd & lstat, lstat & nox,dis & nox and rm & nox. But for some pairs the groups are unclear, for instance rm&ptratio, age & ptratio, ptratio & lstat.
km <-kmeans(boston_scaled2, centers = 2)
str(km)
## List of 9
## $ cluster : Named int [1:506] 2 2 2 2 2 2 2 2 2 2 ...
## ..- attr(*, "names")= chr [1:506] "1" "2" "3" "4" ...
## $ centers : num [1:2, 1:14] 0.724 -0.389 -0.487 0.262 1.143 ...
## ..- attr(*, "dimnames")=List of 2
## .. ..$ : chr [1:2] "1" "2"
## .. ..$ : chr [1:14] "crim" "zn" "indus" "chas" ...
## $ totss : num 7070
## $ withinss : num [1:2] 1891 2686
## $ tot.withinss: num 4577
## $ betweenss : num 2493
## $ size : int [1:2] 177 329
## $ iter : int 1
## $ ifault : int 0
## - attr(*, "class")= chr "kmeans"
Start again with data reloading and scaling
library(MASS)
library(ggplot2)
library(tidyr)
library(cluster)
data("Boston")
boston_scaled3 <- scale(Boston)
boston_scaled3<-as.data.frame(boston_scaled3)
Number of clusters is selected to be 5 and clusters are target classess.
km_4 <-kmeans(boston_scaled3, centers = 5)
lda.fit2 <- lda(km_4$cluster ~., data = boston_scaled3)
lda.fit2
## Call:
## lda(km_4$cluster ~ ., data = boston_scaled3)
##
## Prior probabilities of groups:
## 1 2 3 4 5
## 0.25296443 0.21146245 0.31027668 0.09881423 0.12648221
##
## Group means:
## crim zn indus chas nox rm
## 1 1.0878724 -0.4872402 1.0149946 -0.1492947 1.0187219 -0.4210063
## 2 -0.3243708 -0.4822312 0.6185681 0.1324196 0.4947716 -0.5346882
## 3 -0.3981592 -0.1664810 -0.6090235 -0.2221749 -0.6655615 -0.1199301
## 4 -0.3103881 -0.1159242 -0.4991257 1.0662850 -0.0692028 1.6606848
## 5 -0.4142124 2.2796750 -1.1802049 -0.2108119 -1.1778698 0.7327381
## age dis rad tax ptratio black
## 1 0.7521154 -0.8135370 1.6596029 1.5294129 0.8057784 -0.7784115
## 2 0.7503783 -0.5640394 -0.5954711 -0.1985406 0.1042866 0.0419631
## 3 -0.6336330 0.5362710 -0.5817365 -0.7039306 -0.0756665 0.3655348
## 4 0.2630692 -0.4217934 -0.3042757 -0.5487050 -0.9864145 0.3028535
## 5 -1.4099114 1.5840638 -0.6588648 -0.5713854 -0.8296553 0.3533591
## lstat medv
## 1 0.8914421 -0.75669132
## 2 0.5669361 -0.49061591
## 3 -0.4149421 0.05516096
## 4 -0.9553010 1.76459824
## 5 -0.9664968 0.81972201
##
## Coefficients of linear discriminants:
## LD1 LD2 LD3 LD4
## crim -0.053751141 0.179074873 0.13780108 -0.07519738
## zn 0.062843967 1.465907935 -0.50908589 1.32076958
## indus -0.179836757 -0.391770295 -0.40486479 0.39138090
## chas 0.230845551 -0.111364285 0.41752818 0.17516588
## nox 0.076978215 -0.081264681 -0.04255968 0.44218751
## rm -0.111320904 0.164332062 0.59726088 0.22808090
## age -0.048463133 -0.522072143 0.34421689 0.63414099
## dis 0.291886353 0.306401440 -0.21018069 -0.27013447
## rad -4.160201638 1.135383393 0.44562029 -1.62967439
## tax 0.204066630 0.381083248 -0.11925476 1.00108406
## ptratio 0.009872979 -0.170859777 -0.22250511 0.33481849
## black 0.025657288 0.005723222 -0.01480980 -0.08944504
## lstat -0.105055816 -0.045731798 0.14150418 0.39609928
## medv 0.351343258 0.268482029 0.88984740 0.30142226
##
## Proportion of trace:
## LD1 LD2 LD3 LD4
## 0.7423 0.1680 0.0517 0.0381
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "red", tex = 0.75, choices = c(1,2)){
heads <- coef(x)
arrows(x0 = 0, y0 = 0,
x1 = myscale * heads[,choices[1]],
y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
text(myscale * heads[,choices], labels = row.names(heads),
cex = tex, col=color, pos=3)
}
Biplot drawing next:
plot(lda.fit2, dimen = 2, col=classes, pch=classes)
lda.arrows(lda.fit2, myscale = 1)
Everytime the model is run again, the results change. But rad and zn are standing out, also chas every so often. Arrows for each variable point in the direction of increasing values of that variable.Rad increases meaning higher the value, the more meaningful it is in clustering where it is pointin. Otherwise all variables are around zero meaning they are not influencial
I copied the lines from the instructions and did the package installation
model_predictors <- dplyr::select(train, -crime)
# check the dimensions
dim(model_predictors)
## [1] 404 13
dim(lda.fit$scaling)
## [1] 13 3
# matrix multiplication
matrix_product <- as.matrix(model_predictors) %*% lda.fit$scaling
matrix_product <- as.data.frame(matrix_product)
Then I tried plotting as instucted
library(plotly)
##
## Attaching package: 'plotly'
## The following object is masked from 'package:MASS':
##
## select
## The following object is masked from 'package:ggplot2':
##
## last_plot
## The following object is masked from 'package:stats':
##
## filter
## The following object is masked from 'package:graphics':
##
## layout
plot_ly(x = matrix_product$LD1, y = matrix_product$LD2, z = matrix_product$LD3, type= 'scatter3d', mode='markers')
However, at this point I run into trouble with WebGL. In the help page the cube is rolling but I just did not succeed in R Studio.
hd <- read.csv("http://s3.amazonaws.com/assets.datacamp.com/production/course_2218/datasets/human_development.csv", stringsAsFactors = F)
gii <- read.csv("http://s3.amazonaws.com/assets.datacamp.com/production/course_2218/datasets/gender_inequality.csv", stringsAsFactors = F, na.strings = "..")
#checking the dimension
dim(hd)
## [1] 195 8
dim(gii)
## [1] 195 10
#checking the structure
str(hd)
## 'data.frame': 195 obs. of 8 variables:
## $ HDI.Rank : int 1 2 3 4 5 6 6 8 9 9 ...
## $ Country : chr "Norway" "Australia" "Switzerland" "Denmark" ...
## $ Human.Development.Index..HDI. : num 0.944 0.935 0.93 0.923 0.922 0.916 0.916 0.915 0.913 0.913 ...
## $ Life.Expectancy.at.Birth : num 81.6 82.4 83 80.2 81.6 80.9 80.9 79.1 82 81.8 ...
## $ Expected.Years.of.Education : num 17.5 20.2 15.8 18.7 17.9 16.5 18.6 16.5 15.9 19.2 ...
## $ Mean.Years.of.Education : num 12.6 13 12.8 12.7 11.9 13.1 12.2 12.9 13 12.5 ...
## $ Gross.National.Income..GNI..per.Capita: chr "64,992" "42,261" "56,431" "44,025" ...
## $ GNI.per.Capita.Rank.Minus.HDI.Rank : int 5 17 6 11 9 11 16 3 11 23 ...
str(gii)
## 'data.frame': 195 obs. of 10 variables:
## $ GII.Rank : int 1 2 3 4 5 6 6 8 9 9 ...
## $ Country : chr "Norway" "Australia" "Switzerland" "Denmark" ...
## $ Gender.Inequality.Index..GII. : num 0.067 0.11 0.028 0.048 0.062 0.041 0.113 0.28 0.129 0.157 ...
## $ Maternal.Mortality.Ratio : int 4 6 6 5 6 7 9 28 11 8 ...
## $ Adolescent.Birth.Rate : num 7.8 12.1 1.9 5.1 6.2 3.8 8.2 31 14.5 25.3 ...
## $ Percent.Representation.in.Parliament : num 39.6 30.5 28.5 38 36.9 36.9 19.9 19.4 28.2 31.4 ...
## $ Population.with.Secondary.Education..Female.: num 97.4 94.3 95 95.5 87.7 96.3 80.5 95.1 100 95 ...
## $ Population.with.Secondary.Education..Male. : num 96.7 94.6 96.6 96.6 90.5 97 78.6 94.8 100 95.3 ...
## $ Labour.Force.Participation.Rate..Female. : num 61.2 58.8 61.8 58.7 58.5 53.6 53.1 56.3 61.6 62 ...
## $ Labour.Force.Participation.Rate..Male. : num 68.7 71.8 74.9 66.4 70.6 66.4 68.1 68.9 71 73.8 ...
summary(hd)
## HDI.Rank Country Human.Development.Index..HDI.
## Min. : 1.00 Length:195 Min. :0.3480
## 1st Qu.: 47.75 Class :character 1st Qu.:0.5770
## Median : 94.00 Mode :character Median :0.7210
## Mean : 94.31 Mean :0.6918
## 3rd Qu.:141.25 3rd Qu.:0.8000
## Max. :188.00 Max. :0.9440
## NA's :7
## Life.Expectancy.at.Birth Expected.Years.of.Education
## Min. :49.00 Min. : 4.10
## 1st Qu.:65.75 1st Qu.:11.10
## Median :73.10 Median :13.10
## Mean :71.07 Mean :12.86
## 3rd Qu.:76.80 3rd Qu.:14.90
## Max. :84.00 Max. :20.20
##
## Mean.Years.of.Education Gross.National.Income..GNI..per.Capita
## Min. : 1.400 Length:195
## 1st Qu.: 5.550 Class :character
## Median : 8.400 Mode :character
## Mean : 8.079
## 3rd Qu.:10.600
## Max. :13.100
##
## GNI.per.Capita.Rank.Minus.HDI.Rank
## Min. :-84.0000
## 1st Qu.: -9.0000
## Median : 1.5000
## Mean : 0.1862
## 3rd Qu.: 11.0000
## Max. : 47.0000
## NA's :7
summary(gii)
## GII.Rank Country Gender.Inequality.Index..GII.
## Min. : 1.00 Length:195 Min. :0.0160
## 1st Qu.: 47.75 Class :character 1st Qu.:0.2030
## Median : 94.00 Mode :character Median :0.3935
## Mean : 94.31 Mean :0.3695
## 3rd Qu.:141.25 3rd Qu.:0.5272
## Max. :188.00 Max. :0.7440
## NA's :7 NA's :33
## Maternal.Mortality.Ratio Adolescent.Birth.Rate
## Min. : 1.0 Min. : 0.60
## 1st Qu.: 16.0 1st Qu.: 15.45
## Median : 69.0 Median : 40.95
## Mean : 163.2 Mean : 49.55
## 3rd Qu.: 230.0 3rd Qu.: 71.78
## Max. :1100.0 Max. :204.80
## NA's :10 NA's :5
## Percent.Representation.in.Parliament
## Min. : 0.00
## 1st Qu.:12.47
## Median :19.50
## Mean :20.60
## 3rd Qu.:27.02
## Max. :57.50
## NA's :3
## Population.with.Secondary.Education..Female.
## Min. : 0.9
## 1st Qu.: 27.8
## Median : 55.7
## Mean : 54.8
## 3rd Qu.: 81.8
## Max. :100.0
## NA's :26
## Population.with.Secondary.Education..Male.
## Min. : 3.20
## 1st Qu.: 38.30
## Median : 60.00
## Mean : 60.29
## 3rd Qu.: 85.80
## Max. :100.00
## NA's :26
## Labour.Force.Participation.Rate..Female.
## Min. :13.50
## 1st Qu.:44.50
## Median :53.30
## Mean :52.61
## 3rd Qu.:62.62
## Max. :88.10
## NA's :11
## Labour.Force.Participation.Rate..Male.
## Min. :44.20
## 1st Qu.:68.88
## Median :75.55
## Mean :74.74
## 3rd Qu.:80.15
## Max. :95.50
## NA's :11
Renaming the columns:
names(hd)[names(hd) == "Human.Development.Index..HDI."] <- "HDI"
names(hd)[names(hd) == "Expected.Years.of.Education"] <- "EYE"
names(hd)[names(hd) == "Life.Expectancy.at.Birth"] <- "LEB"
names(hd)[names(hd) == "Mean.Years.of.Education"] <- "MYE"
names(hd)[names(hd) == "Gender.Inequality.Index..GII."] <- "GII"
names(hd)[names(hd) == "Maternal.Mortality.Ratio"] <- "MMR"
names(hd)[names(hd) == "Percent.Representation.in.Parliament"] <- "PerParliament"
names(hd)[names(hd) == "Population.with.Secondary.Education..Female."] <- "SecEducFemal"
names(hd)[names(hd) == "Gross.National.Income..GNI..per.Capita"] <- "GNIncPerCap"
names(hd)[names(hd) == "GNI.per.Capita.Rank.Minus.HDI.Rank"] <- "GNIMinusHDIRank"
names(gii)[names(gii) == "Adolescent.Birth.Rate"] <- "ADBR"
names(gii)[names(gii) == "Expected.Years.of.Education"] <- "EYE"
names(gii)[names(gii) == "Life.Expectancy.at.Birth"] <- "LEB"
names(gii)[names(gii) == "Mean.Years.of.Education"] <- "MYE"
names(gii)[names(gii) == "Gender.Inequality.Index..GII."] <- "GII"
names(gii)[names(gii) == "Maternal.Mortality.Ratio"] <- "MMR"
names(gii)[names(gii) == "Percent.Representation.in.Parliament"] <- "PerParliament"
names(gii)[names(gii) == "Population.with.Secondary.Education..Male."] <- "SecEducMale"
names(gii)[names(gii) == "Population.with.Secondary.Education..Female."] <- "SecEducFemal"
names(gii)[names(gii) == "Gross.National.Income..GNI..per.Capita"] <- "GNIncPerCap"
names(gii)[names(gii) == "Labour.Force.Participation.Rate..Female."] <- "LabForParFem"
names(gii)[names(gii) == "Labour.Force.Participation.Rate..Male."] <- "LabForParMale"
head(hd)
## HDI.Rank Country HDI LEB EYE MYE GNIncPerCap GNIMinusHDIRank
## 1 1 Norway 0.944 81.6 17.5 12.6 64,992 5
## 2 2 Australia 0.935 82.4 20.2 13.0 42,261 17
## 3 3 Switzerland 0.930 83.0 15.8 12.8 56,431 6
## 4 4 Denmark 0.923 80.2 18.7 12.7 44,025 11
## 5 5 Netherlands 0.922 81.6 17.9 11.9 45,435 9
## 6 6 Germany 0.916 80.9 16.5 13.1 43,919 11
head(gii)
## GII.Rank Country GII MMR ADBR PerParliament SecEducFemal
## 1 1 Norway 0.067 4 7.8 39.6 97.4
## 2 2 Australia 0.110 6 12.1 30.5 94.3
## 3 3 Switzerland 0.028 6 1.9 28.5 95.0
## 4 4 Denmark 0.048 5 5.1 38.0 95.5
## 5 5 Netherlands 0.062 6 6.2 36.9 87.7
## 6 6 Germany 0.041 7 3.8 36.9 96.3
## SecEducMale LabForParFem LabForParMale
## 1 96.7 61.2 68.7
## 2 94.6 58.8 71.8
## 3 96.6 61.8 74.9
## 4 96.6 58.7 66.4
## 5 90.5 58.5 70.6
## 6 97.0 53.6 66.4
Work summary Codes are available at
Data set is about human development indeces (HDI). United Nations Development Programme has collected it and it contains many indeces that can be used for evaluating nation’s development in human outcomes. Traditional economic GNI values alone do not describe the humanity of the state and therefore complementary measures are needed. Such measures are for instance life expectancy, population with secondary education (female/male) etc. More information about the HDI is found here
Data is loaded from the given address
human <- read.table("http://s3.amazonaws.com/assets.datacamp.com/production/course_2218/datasets/human1.txt", sep =",", header = T)
Next I check the data structure and check that the variables are the same I expected.
str(human)
## 'data.frame': 195 obs. of 19 variables:
## $ HDI.Rank : int 1 2 3 4 5 6 6 8 9 9 ...
## $ Country : Factor w/ 195 levels "Afghanistan",..: 129 10 169 48 124 67 84 186 34 125 ...
## $ HDI : num 0.944 0.935 0.93 0.923 0.922 0.916 0.916 0.915 0.913 0.913 ...
## $ Life.Exp : num 81.6 82.4 83 80.2 81.6 80.9 80.9 79.1 82 81.8 ...
## $ Edu.Exp : num 17.5 20.2 15.8 18.7 17.9 16.5 18.6 16.5 15.9 19.2 ...
## $ Edu.Mean : num 12.6 13 12.8 12.7 11.9 13.1 12.2 12.9 13 12.5 ...
## $ GNI : Factor w/ 194 levels "1,096","1,123",..: 166 135 156 139 140 137 127 154 134 117 ...
## $ GNI.Minus.Rank: int 5 17 6 11 9 11 16 3 11 23 ...
## $ GII.Rank : int 1 2 3 4 5 6 6 8 9 9 ...
## $ GII : num 0.067 0.11 0.028 0.048 0.062 0.041 0.113 0.28 0.129 0.157 ...
## $ Mat.Mor : int 4 6 6 5 6 7 9 28 11 8 ...
## $ Ado.Birth : num 7.8 12.1 1.9 5.1 6.2 3.8 8.2 31 14.5 25.3 ...
## $ Parli.F : num 39.6 30.5 28.5 38 36.9 36.9 19.9 19.4 28.2 31.4 ...
## $ Edu2.F : num 97.4 94.3 95 95.5 87.7 96.3 80.5 95.1 100 95 ...
## $ Edu2.M : num 96.7 94.6 96.6 96.6 90.5 97 78.6 94.8 100 95.3 ...
## $ Labo.F : num 61.2 58.8 61.8 58.7 58.5 53.6 53.1 56.3 61.6 62 ...
## $ Labo.M : num 68.7 71.8 74.9 66.4 70.6 66.4 68.1 68.9 71 73.8 ...
## $ Edu2.FM : num 1.007 0.997 0.983 0.989 0.969 ...
## $ Labo.FM : num 0.891 0.819 0.825 0.884 0.829 ...
names(human)
## [1] "HDI.Rank" "Country" "HDI" "Life.Exp"
## [5] "Edu.Exp" "Edu.Mean" "GNI" "GNI.Minus.Rank"
## [9] "GII.Rank" "GII" "Mat.Mor" "Ado.Birth"
## [13] "Parli.F" "Edu2.F" "Edu2.M" "Labo.F"
## [17] "Labo.M" "Edu2.FM" "Labo.FM"
Commas are replaced and GNI changed to numeric. I also check GNI is now really a numeric variable.
human$GNI <- as.numeric(human$GNI)
str(human$GNI)
## num [1:195] 166 135 156 139 140 137 127 154 134 117 ...
Only required columns are kept and NA rows are removed by usin complete.cases, country name column is removed:
library(dplyr)
human <- read.table("http://s3.amazonaws.com/assets.datacamp.com/production/course_2218/datasets/human1.txt", sep =",", header = T)
human$GNI <- as.numeric(human$GNI)
keep <- c("Country", "Edu2.FM", "Labo.FM", "Life.Exp", "Edu.Exp", "GNI", "Mat.Mor", "Ado.Birth", "Parli.F")
human <- select(human, one_of(keep))
data.frame(human[-1], comp = complete.cases(human))
## Edu2.FM Labo.FM Life.Exp Edu.Exp GNI Mat.Mor Ado.Birth Parli.F
## 1 1.0072389 0.8908297 81.6 17.5 166 4 7.8 39.6
## 2 0.9968288 0.8189415 82.4 20.2 135 6 12.1 30.5
## 3 0.9834369 0.8251001 83.0 15.8 156 6 1.9 28.5
## 4 0.9886128 0.8840361 80.2 18.7 139 5 5.1 38.0
## 5 0.9690608 0.8286119 81.6 17.9 140 6 6.2 36.9
## 6 0.9927835 0.8072289 80.9 16.5 137 7 3.8 36.9
## 7 1.0241730 0.7797357 80.9 18.6 127 9 8.2 19.9
## 8 1.0031646 0.8171263 79.1 16.5 154 28 31.0 19.4
## 9 1.0000000 0.8676056 82.0 15.9 134 11 14.5 28.2
## 10 0.9968520 0.8401084 81.8 19.2 117 8 25.3 31.4
## 11 0.9148148 0.7616580 83.0 15.4 180 6 6.0 25.3
## 12 0.9116162 0.7566372 84.0 15.6 155 NA 3.3 NA
## 13 NA NA 80.0 15.0 181 NA NA 20.0
## 14 0.9908362 0.8880707 82.2 15.8 141 4 6.5 43.6
## 15 0.9989990 0.8107715 80.7 16.2 126 8 25.8 23.5
## 16 0.9934498 0.9108527 82.6 19.0 121 4 11.5 41.3
## 17 0.8641975 0.6948682 81.9 16.9 119 27 2.2 16.3
## 18 0.9667812 0.8379161 82.4 16.0 115 2 7.8 22.5
## 19 1.0000000 0.7848297 81.7 13.9 157 11 8.3 28.3
## 20 1.0139860 0.6931818 83.5 15.3 122 6 5.4 11.6
## 21 0.9348613 0.8010118 80.8 16.3 133 6 6.7 42.4
## 22 0.9375000 0.8230519 82.2 16.0 123 12 5.7 25.7
## 23 1.0000000 0.8064993 81.4 15.7 136 4 4.1 30.3
## 24 1.0000000 0.8703125 80.8 17.1 125 4 9.2 42.5
## 25 0.9775510 0.8275316 80.4 16.8 99 7 0.6 27.7
## 26 0.9138167 0.7978723 82.6 17.3 116 4 10.6 38.0
## 27 0.8844720 0.6655462 83.1 16.0 118 4 4.0 30.1
## 28 1.0020060 0.7481698 78.6 16.4 98 5 4.9 18.9
## 29 0.8880597 0.7072000 80.9 17.6 93 5 11.9 21.0
## 30 1.0000000 0.8156749 76.8 16.5 94 11 16.8 19.8
## 31 0.9424779 0.6985392 78.8 14.5 177 27 23.0 NA
## 32 0.9302326 0.7876231 80.2 14.0 101 10 5.5 12.5
## 33 1.1305085 0.5319372 78.2 13.8 37 6 9.5 0.0
## 34 1.0040568 NA 81.3 13.5 138 NA NA 50.0
## 35 0.9959799 0.7448980 76.3 15.1 96 7 15.9 18.7
## 36 0.9286550 0.7534669 77.4 15.5 90 3 12.2 22.1
## 37 0.9448568 0.8291233 73.3 16.4 92 11 10.6 23.4
## 38 0.8772379 0.5716440 80.6 14.4 100 9 18.2 13.0
## 39 0.8605974 0.2579821 74.3 16.3 153 16 10.2 19.9
## 40 0.9774306 0.6333333 76.3 17.9 85 69 54.4 36.8
## 41 1.1944444 0.5054348 77.0 13.3 165 8 27.6 17.5
## 42 0.9594241 0.6577540 81.7 15.2 83 22 55.3 15.8
## 43 0.9896266 0.8293051 80.9 16.3 95 8 12.6 31.3
## 44 0.9918946 0.7466667 75.2 15.4 89 14 12.1 10.1
## 45 1.1031128 0.4510932 76.6 14.4 124 22 13.8 15.0
## 46 0.9989899 0.8121302 74.2 15.2 86 13 13.5 18.0
## 47 0.9081197 0.7654110 77.3 14.8 65 13 12.7 25.8
## 48 0.9875666 0.5246691 74.4 14.7 185 14 14.5 1.5
## 49 0.8891235 0.7504363 76.2 15.2 46 7 15.2 17.3
## 50 0.9436009 0.7939778 71.3 15.7 59 1 20.6 30.1
## 51 0.9686486 0.7963738 70.1 14.7 87 24 25.7 14.5
## 52 0.8266200 0.3510896 76.8 13.6 120 11 10.6 9.6
## 53 0.9358696 0.7503852 74.7 14.2 61 33 31.0 12.0
## 54 1.0815109 0.7239583 77.2 15.5 64 14 58.3 11.5
## 55 1.0410959 0.8738966 75.4 12.6 84 37 28.5 16.7
## 56 0.9645749 0.8690629 69.4 15.0 81 26 29.9 20.1
## 57 1.0205245 0.8603133 75.6 15.4 34 52 48.4 19.6
## 58 NA NA 76.1 14.0 79 NA 49.3 25.7
## 59 0.9717868 0.8118644 74.2 14.4 50 5 35.9 20.4
## 60 NA NA 72.7 13.7 42 NA NA 10.3
## 61 1.0821643 0.5990220 77.6 13.3 62 85 78.5 19.3
## 62 0.9130435 0.5880795 74.7 12.7 88 29 5.7 14.2
## 63 0.8517241 0.5876011 74.4 15.6 60 73 30.9 11.6
## 64 1.0045045 NA 73.1 13.4 91 NA 56.3 43.8
## 65 0.9802956 0.7019868 70.4 12.3 97 84 34.8 24.7
## 66 0.7934783 0.7307061 74.9 14.4 32 16 16.9 34.0
## 67 0.9428934 0.6200000 79.4 13.8 170 80 43.1 48.9
## 68 0.9566787 0.3286319 79.3 13.8 57 16 12.0 3.1
## 69 1.0039604 0.5898734 79.4 13.9 41 38 60.8 33.3
## 70 0.9201183 0.2255435 75.4 15.1 49 23 31.6 3.1
## 71 1.1141732 0.6452020 74.2 14.2 54 110 83.2 17.0
## 72 0.6500000 0.4152542 75.3 14.5 63 20 30.9 14.4
## 73 0.9515707 0.4600262 74.9 13.7 189 29 16.9 5.8
## 74 0.9191419 0.5644556 76.8 13.1 53 49 63.4 37.1
## 75 1.0419847 0.7351485 74.5 15.2 48 69 70.8 9.6
## 76 0.9676375 0.7523302 74.9 13.8 168 41 46.8 11.3
## 77 NA NA 73.8 12.9 80 NA NA 6.7
## 78 0.9620123 0.9037356 70.8 11.9 56 26 40.0 15.6
## 79 NA NA 73.4 15.8 24 23 35.4 25.0
## 80 0.8853503 0.2342342 74.0 13.5 26 50 26.5 11.6
## 81 0.7230216 0.6385185 75.4 13.4 28 7 18.3 33.3
## 82 0.9562044 0.7952167 71.0 15.1 183 23 25.7 11.8
## 83 0.8612903 0.2105263 74.8 14.0 38 89 10.0 25.7
## 84 0.8517398 0.8080569 74.6 13.1 25 89 50.7 22.3
## 85 0.9306030 0.6854962 77.8 11.8 192 21 15.3 20.7
## 86 0.9894737 0.7465565 74.7 12.3 182 29 27.1 10.7
## 87 0.6432665 0.5951134 76.5 13.6 187 8 15.1 19.3
## 88 1.0177665 0.6614268 75.9 14.2 22 87 77.0 41.6
## 89 NA 0.8228346 75.1 12.6 188 34 56.3 20.7
## 90 0.8164117 0.8160920 75.8 13.1 35 32 8.6 23.6
## 91 0.9953488 0.5208333 70.0 15.7 173 59 42.8 14.0
## 92 1.0142687 0.8167388 69.4 14.6 23 68 18.7 14.9
## 93 0.8750000 0.7967782 74.4 13.5 40 26 41.0 6.1
## 94 1.2801724 NA 77.8 12.7 193 NA NA 21.9
## 95 1.3245823 0.3926702 71.6 14.0 47 15 2.5 16.0
## 96 0.7114967 0.3540197 74.8 14.6 20 46 4.6 31.3
## 97 1.0233813 0.7001255 74.0 13.5 30 83 68.5 20.9
## 98 NA 0.7141026 72.9 13.4 191 45 54.5 13.0
## 99 1.0541311 0.7912553 75.7 12.4 172 80 70.1 16.7
## 100 0.9909400 0.7171582 72.8 14.7 142 120 18.1 0.0
## 101 1.0079156 0.5978129 70.0 13.6 174 45 71.4 13.3
## 102 1.0470810 0.6526718 73.5 13.1 29 100 99.6 19.1
## 103 0.9469214 0.5886628 71.1 12.7 51 130 35.2 11.8
## 104 0.8348624 0.7251613 76.8 13.0 33 31 4.2 5.9
## 105 1.0716667 0.4023973 73.4 12.9 145 58 28.3 6.1
## 106 0.9448010 0.8811275 64.5 12.5 58 170 44.2 9.5
## 107 0.9689441 0.8506787 71.6 11.9 144 21 29.3 20.8
## 108 0.7244224 0.3168449 71.1 13.5 21 45 43.0 2.2
## 109 NA 0.6098830 65.6 10.8 39 61 18.0 25.8
## 110 1.4930748 0.8593272 64.4 12.5 55 240 103.0 16.2
## 111 0.8109756 0.6104513 68.9 13.0 190 190 48.3 17.1
## 112 0.8558140 0.6568396 72.9 11.9 175 110 67.0 16.8
## 113 0.9074074 0.2319277 72.9 13.0 131 NA 45.8 NA
## 114 NA 0.6362434 68.4 11.5 150 36 38.8 16.4
## 115 1.0345369 0.6411543 68.2 11.3 176 120 46.8 27.1
## 116 0.8440367 0.6050633 73.0 12.3 171 69 76.0 27.4
## 117 0.9578393 0.7355372 57.4 13.6 31 140 50.9 40.7
## 118 0.8342697 0.8880779 75.8 11.9 143 49 29.0 24.3
## 119 0.8054146 0.7935723 68.3 13.2 152 200 71.9 51.8
## 120 0.9762397 0.7044025 70.6 12.5 102 75 29.3 23.3
## 121 0.5537849 0.2134670 69.4 10.1 43 67 68.7 26.5
## 122 NA 0.6152927 73.3 13.5 160 53 70.6 20.8
## 123 NA NA 69.1 11.7 108 96 18.6 0.0
## 124 1.2615063 0.5291925 66.4 10.3 161 250 88.5 31.3
## 125 1.0287206 0.5902864 74.9 11.5 128 100 100.8 39.1
## 126 0.6854305 0.3496042 74.0 11.6 163 120 35.8 11.0
## 127 0.9680233 0.8587127 64.8 11.3 186 130 54.9 37.7
## 128 0.9439655 0.5589569 71.8 10.7 164 140 97.2 13.3
## 129 1.0427632 0.7639429 69.4 11.2 73 44 42.8 15.2
## 130 0.4770318 0.3379224 68.0 11.7 148 190 32.8 12.2
## 131 1.0852713 0.5162847 73.1 11.1 114 120 84.0 25.8
## 132 0.9855072 0.8639896 69.5 12.6 169 120 40.9 8.3
## 133 NA 0.4842520 68.2 11.7 147 270 52.2 38.5
## 134 0.7283951 0.1856946 69.6 12.3 74 49 41.6 12.4
## 135 NA 0.7687500 71.9 10.6 76 86 44.8 0.0
## 136 0.8446809 0.9383562 62.3 11.1 159 410 126.7 11.5
## 137 NA NA 66.0 12.3 71 130 16.6 8.7
## 138 NA 0.8752711 57.6 9.0 82 290 112.6 19.7
## 139 0.5863636 0.8539720 60.1 13.5 111 280 125.4 12.7
## 140 0.6986090 0.9425770 61.4 11.5 113 380 58.4 10.9
## 141 0.6189189 0.9646018 66.2 10.6 130 NA 65.0 25.0
## 142 0.8256659 0.6825208 71.6 10.0 104 170 80.6 20.0
## 143 0.4323144 0.9109827 68.4 10.9 78 170 44.3 19.0
## 144 NA 0.5822622 66.5 11.3 77 210 65.1 18.2
## 145 0.8057325 0.8591160 61.6 11.0 75 400 93.6 20.8
## 146 0.4633508 0.9173364 69.6 12.4 68 190 73.7 29.5
## 147 0.4186551 0.2967431 66.2 7.8 132 170 27.3 19.7
## 148 1.4967320 0.9137303 65.9 8.6 129 200 12.1 4.7
## 149 NA 0.8231469 52.3 11.4 162 460 170.2 36.8
## 150 0.8423077 0.6131285 49.0 11.3 149 310 72.0 14.7
## 151 0.5894737 0.9767184 65.0 9.2 70 410 122.7 36.0
## 152 NA 0.7566719 52.8 9.0 146 560 119.6 6.6
## 153 0.6103152 0.8307292 55.5 10.4 76 590 115.8 27.1
## 154 NA 0.9569061 65.1 10.3 5 440 122.8 20.5
## 155 0.7854839 0.9275362 57.5 10.9 15 470 60.3 35.1
## 156 0.3971292 0.3628319 63.1 8.5 110 320 73.3 22.2
## 157 NA 0.6759494 67.9 9.2 11 130 64.9 2.0
## 158 0.5241379 0.9527027 62.6 9.9 72 220 62.1 2.7
## 159 NA 0.4394507 63.3 11.5 8 350 51.1 3.0
## 160 0.3220974 0.3518006 63.8 9.2 109 270 47.0 0.7
## 161 1.1526316 0.8027211 49.8 11.1 106 490 89.4 26.8
## 162 0.3995037 0.9913899 59.7 12.2 4 450 91.5 17.6
## 163 0.6363636 0.8577465 62.8 8.7 16 380 42.0 3.5
## 164 0.9090909 1.0128957 64.2 10.3 9 320 33.6 57.5
## 165 0.6835821 0.9570707 58.5 9.8 14 360 126.6 35.0
## 166 0.4185185 0.8633461 59.6 11.1 17 340 90.2 8.4
## 167 0.6648352 0.4118421 63.5 7.0 112 360 84.0 23.8
## 168 NA 0.5361891 62.0 6.4 105 230 18.6 12.7
## 169 NA NA 55.7 7.6 69 730 75.3 24.3
## 170 0.4675325 0.7500000 66.5 7.9 67 320 94.4 42.7
## 171 0.1979866 0.1987421 60.4 9.3 19 400 86.8 27.6
## 172 0.4651163 0.6437346 51.5 8.9 103 720 130.3 9.2
## 173 0.5138889 1.0380368 62.8 10.8 178 510 144.8 16.7
## 174 0.4285714 0.8756999 64.1 8.5 7 420 78.4 25.5
## 175 0.5523810 0.8709288 60.2 8.8 10 430 115.8 9.4
## 176 0.3950617 0.9658470 58.7 9.8 167 730 135.3 8.2
## 177 0.3918575 0.8981481 60.9 9.5 184 640 117.4 10.7
## 178 NA 0.8687898 55.2 9.0 6 560 99.3 13.7
## 179 0.5099338 0.6240786 58.0 8.4 12 550 175.6 9.5
## 180 0.2258065 1.0326087 55.1 9.3 2 480 137.8 39.6
## 181 0.4608295 0.9521739 50.9 8.6 18 1100 100.7 12.4
## 182 NA 0.8378033 58.8 8.7 1 650 131.0 21.9
## 183 0.2812500 0.8566667 58.7 7.8 13 400 115.4 13.3
## 184 0.6385542 1.0158537 56.7 10.1 179 740 30.3 34.9
## 185 0.1717172 0.8080808 51.6 7.4 66 980 152.0 14.9
## 186 NA 0.8908686 63.7 4.1 3 380 65.3 22.0
## 187 0.3782772 0.8531140 50.7 7.2 158 880 98.3 12.5
## 188 0.3076923 0.4459309 61.4 5.4 194 630 204.8 13.3
## 189 0.7289916 0.3081009 70.6 12.0 52 155 45.4 14.0
## 190 0.8250377 0.7884131 74.0 12.7 27 72 21.2 18.7
## 191 0.8784119 0.6514286 72.3 13.6 36 28 30.8 19.0
## 192 0.9836957 0.6729323 75.0 14.0 44 85 68.3 27.0
## 193 0.5329670 0.3711083 68.4 11.2 151 183 38.7 17.5
## 194 0.7015873 0.8537859 58.5 9.6 107 506 109.7 22.5
## 195 0.8333333 0.6558018 71.5 12.2 45 210 47.4 21.8
## comp
## 1 TRUE
## 2 TRUE
## 3 TRUE
## 4 TRUE
## 5 TRUE
## 6 TRUE
## 7 TRUE
## 8 TRUE
## 9 TRUE
## 10 TRUE
## 11 TRUE
## 12 FALSE
## 13 FALSE
## 14 TRUE
## 15 TRUE
## 16 TRUE
## 17 TRUE
## 18 TRUE
## 19 TRUE
## 20 TRUE
## 21 TRUE
## 22 TRUE
## 23 TRUE
## 24 TRUE
## 25 TRUE
## 26 TRUE
## 27 TRUE
## 28 TRUE
## 29 TRUE
## 30 TRUE
## 31 FALSE
## 32 TRUE
## 33 TRUE
## 34 FALSE
## 35 TRUE
## 36 TRUE
## 37 TRUE
## 38 TRUE
## 39 TRUE
## 40 TRUE
## 41 TRUE
## 42 TRUE
## 43 TRUE
## 44 TRUE
## 45 TRUE
## 46 TRUE
## 47 TRUE
## 48 TRUE
## 49 TRUE
## 50 TRUE
## 51 TRUE
## 52 TRUE
## 53 TRUE
## 54 TRUE
## 55 TRUE
## 56 TRUE
## 57 TRUE
## 58 FALSE
## 59 TRUE
## 60 FALSE
## 61 TRUE
## 62 TRUE
## 63 TRUE
## 64 FALSE
## 65 TRUE
## 66 TRUE
## 67 TRUE
## 68 TRUE
## 69 TRUE
## 70 TRUE
## 71 TRUE
## 72 TRUE
## 73 TRUE
## 74 TRUE
## 75 TRUE
## 76 TRUE
## 77 FALSE
## 78 TRUE
## 79 FALSE
## 80 TRUE
## 81 TRUE
## 82 TRUE
## 83 TRUE
## 84 TRUE
## 85 TRUE
## 86 TRUE
## 87 TRUE
## 88 TRUE
## 89 FALSE
## 90 TRUE
## 91 TRUE
## 92 TRUE
## 93 TRUE
## 94 FALSE
## 95 TRUE
## 96 TRUE
## 97 TRUE
## 98 FALSE
## 99 TRUE
## 100 TRUE
## 101 TRUE
## 102 TRUE
## 103 TRUE
## 104 TRUE
## 105 TRUE
## 106 TRUE
## 107 TRUE
## 108 TRUE
## 109 FALSE
## 110 TRUE
## 111 TRUE
## 112 TRUE
## 113 FALSE
## 114 FALSE
## 115 TRUE
## 116 TRUE
## 117 TRUE
## 118 TRUE
## 119 TRUE
## 120 TRUE
## 121 TRUE
## 122 FALSE
## 123 FALSE
## 124 TRUE
## 125 TRUE
## 126 TRUE
## 127 TRUE
## 128 TRUE
## 129 TRUE
## 130 TRUE
## 131 TRUE
## 132 TRUE
## 133 FALSE
## 134 TRUE
## 135 FALSE
## 136 TRUE
## 137 FALSE
## 138 FALSE
## 139 TRUE
## 140 TRUE
## 141 FALSE
## 142 TRUE
## 143 TRUE
## 144 FALSE
## 145 TRUE
## 146 TRUE
## 147 TRUE
## 148 TRUE
## 149 FALSE
## 150 TRUE
## 151 TRUE
## 152 FALSE
## 153 TRUE
## 154 FALSE
## 155 TRUE
## 156 TRUE
## 157 FALSE
## 158 TRUE
## 159 FALSE
## 160 TRUE
## 161 TRUE
## 162 TRUE
## 163 TRUE
## 164 TRUE
## 165 TRUE
## 166 TRUE
## 167 TRUE
## 168 FALSE
## 169 FALSE
## 170 TRUE
## 171 TRUE
## 172 TRUE
## 173 TRUE
## 174 TRUE
## 175 TRUE
## 176 TRUE
## 177 TRUE
## 178 FALSE
## 179 TRUE
## 180 TRUE
## 181 TRUE
## 182 FALSE
## 183 TRUE
## 184 TRUE
## 185 TRUE
## 186 FALSE
## 187 TRUE
## 188 TRUE
## 189 TRUE
## 190 TRUE
## 191 TRUE
## 192 TRUE
## 193 TRUE
## 194 TRUE
## 195 TRUE
# filter out all rows with NA values
human_ <- filter(human, complete.cases(human))
tail(human_,10)
## Country Edu2.FM Labo.FM Life.Exp Edu.Exp
## 153 Chad 0.1717172 0.8080808 51.6 7.4
## 154 Central African Republic 0.3782772 0.8531140 50.7 7.2
## 155 Niger 0.3076923 0.4459309 61.4 5.4
## 156 Arab States 0.7289916 0.3081009 70.6 12.0
## 157 East Asia and the Pacific 0.8250377 0.7884131 74.0 12.7
## 158 Europe and Central Asia 0.8784119 0.6514286 72.3 13.6
## 159 Latin America and the Caribbean 0.9836957 0.6729323 75.0 14.0
## 160 South Asia 0.5329670 0.3711083 68.4 11.2
## 161 Sub-Saharan Africa 0.7015873 0.8537859 58.5 9.6
## 162 World 0.8333333 0.6558018 71.5 12.2
## GNI Mat.Mor Ado.Birth Parli.F
## 153 66 980 152.0 14.9
## 154 158 880 98.3 12.5
## 155 194 630 204.8 13.3
## 156 52 155 45.4 14.0
## 157 27 72 21.2 18.7
## 158 36 28 30.8 19.0
## 159 44 85 68.3 27.0
## 160 151 183 38.7 17.5
## 161 107 506 109.7 22.5
## 162 45 210 47.4 21.8
last <- nrow(human_) - 7
human_ <- human[1:last, ]
rownames(human_) <- human_$Country
#country names column removal
human_ <- select(human_, -Country)
dim(human_)
## [1] 155 8
human <-human_
str(human)
## 'data.frame': 155 obs. of 8 variables:
## $ Edu2.FM : num 1.007 0.997 0.983 0.989 0.969 ...
## $ Labo.FM : num 0.891 0.819 0.825 0.884 0.829 ...
## $ Life.Exp : num 81.6 82.4 83 80.2 81.6 80.9 80.9 79.1 82 81.8 ...
## $ Edu.Exp : num 17.5 20.2 15.8 18.7 17.9 16.5 18.6 16.5 15.9 19.2 ...
## $ GNI : num 166 135 156 139 140 137 127 154 134 117 ...
## $ Mat.Mor : int 4 6 6 5 6 7 9 28 11 8 ...
## $ Ado.Birth: num 7.8 12.1 1.9 5.1 6.2 3.8 8.2 31 14.5 25.3 ...
## $ Parli.F : num 39.6 30.5 28.5 38 36.9 36.9 19.9 19.4 28.2 31.4 ...
Not all the rows are countries and therefore regions are taken out. The number of rows decreases to 155 and there are 8 variables as it should be.
Although my data wrangling part seemed to be successfull, I read the wrangled data set and name it to human2.
human2 <- read.table("http://s3.amazonaws.com/assets.datacamp.com/production/course_2218/datasets/human2.txt", sep =",", header = T)
str(human2)
## 'data.frame': 155 obs. of 8 variables:
## $ Edu2.FM : num 1.007 0.997 0.983 0.989 0.969 ...
## $ Labo.FM : num 0.891 0.819 0.825 0.884 0.829 ...
## $ Edu.Exp : num 17.5 20.2 15.8 18.7 17.9 16.5 18.6 16.5 15.9 19.2 ...
## $ Life.Exp : num 81.6 82.4 83 80.2 81.6 80.9 80.9 79.1 82 81.8 ...
## $ GNI : int 64992 42261 56431 44025 45435 43919 39568 52947 42155 32689 ...
## $ Mat.Mor : int 4 6 6 5 6 7 9 28 11 8 ...
## $ Ado.Birth: num 7.8 12.1 1.9 5.1 6.2 3.8 8.2 31 14.5 25.3 ...
## $ Parli.F : num 39.6 30.5 28.5 38 36.9 36.9 19.9 19.4 28.2 31.4 ...
As catter plot matrix shows, Edu.Exp, Parli.F and Edu2.FM seem to be quite normally distributed. Ado.Birth, Mat.Mor and GNI are skewed to the right. Labo.FM is skewed to the left.
library(GGally)
library(ggplot2)
ggpairs(human2, mapping = aes(), title="Scatter plot matrix, distributions ",lower = list(combo = wrap("facethist", bins = 20)))
summary(human2)
## Edu2.FM Labo.FM Edu.Exp Life.Exp
## Min. :0.1717 Min. :0.1857 Min. : 5.40 Min. :49.00
## 1st Qu.:0.7264 1st Qu.:0.5984 1st Qu.:11.25 1st Qu.:66.30
## Median :0.9375 Median :0.7535 Median :13.50 Median :74.20
## Mean :0.8529 Mean :0.7074 Mean :13.18 Mean :71.65
## 3rd Qu.:0.9968 3rd Qu.:0.8535 3rd Qu.:15.20 3rd Qu.:77.25
## Max. :1.4967 Max. :1.0380 Max. :20.20 Max. :83.50
## GNI Mat.Mor Ado.Birth Parli.F
## Min. : 581 Min. : 1.0 Min. : 0.60 Min. : 0.00
## 1st Qu.: 4198 1st Qu.: 11.5 1st Qu.: 12.65 1st Qu.:12.40
## Median : 12040 Median : 49.0 Median : 33.60 Median :19.30
## Mean : 17628 Mean : 149.1 Mean : 47.16 Mean :20.91
## 3rd Qu.: 24512 3rd Qu.: 190.0 3rd Qu.: 71.95 3rd Qu.:27.95
## Max. :123124 Max. :1100.0 Max. :204.80 Max. :57.50
Expected years of education and life expectancy are most strongly positively correlated.The strongest negative correlation is between maternal mortality ratio and life expectancy. On the other hand, gross national income & Labour Force Participation Rate (Female) and Population with Secondary Education (Female) & Labour Force Participation Rate (Female) seem not to correlate at all. This is clearly visible also in correlation matrix visualization
library(corrplot)
## corrplot 0.84 loaded
cor_matrix<-cor(human2)
corrplot(cor_matrix, method="circle", type="upper",cl.pos="b", tl.pos="d", tl.cex=0.6)
### PCA analysis
The first PCA is created with non-standardised data.
pca_human <- prcomp(human2)
s<-summary(pca_human)
pca_pr_nonst <- round(100*s$importance[2,], digits = 1)
pc_lab_nonst <- paste0(names(pca_pr_nonst), " (", pca_pr_nonst, "%)")
biplot(pca_human, cex = c(0.8, 1), col = c("grey40", "deeppink2"), xlab = pc_lab_nonst[1], ylab = pc_lab_nonst[2])
pca_pr_nonst
## PC1 PC2 PC3 PC4 PC5 PC6 PC7 PC8
## 100 0 0 0 0 0 0 0
The picture difficult to interpret. GNI has the biggest variance here and it stands out. Printing out the variance percentages shows clearly how the PC1 seems to capture all the variance. Also the loading values are very large. However, next then the same is done with standardized data
human_std <- scale(human2)
pca_human2 <- prcomp(human_std)
s<-summary(pca_human2)
pca_pr <- round(100*s$importance[2,], digits = 1)
pc_lab <- paste0(names(pca_pr), " (", pca_pr, "%)")
biplot(pca_human2, cex = c(0.8, 1), col = c("grey40", "deeppink2"), xlab = pc_lab[1], ylab = pc_lab[2])
pca_pr
## PC1 PC2 PC3 PC4 PC5 PC6 PC7 PC8
## 53.6 16.2 9.6 7.6 5.5 3.6 2.6 1.3
It is obvious that standardisation is required before PCA in this case. In fact, it is usually recommended, because PCA is sensitive to the relative scaling of the original features and assumes features with larger variance to be more important to those with smaller variance.
With standardization, GNI is no longer as strongly standing out but it is possible to see other variables as well. Gross National Income naturally creates very large numbers in comparison e.g. life-expectansy that is not usually over 80 years. Without standardisation GNI is overemphasized.
When standardized biplot is analysed, Labour Force Participation Rate (Female) and Percent Female Representation in Parliament have small angle and they are positively correlated meaning that the countries where females are active in labour force have them in the parliament as well. They also strongly contribute to PC2.
Maternal mortality ratio and Adolescent Birth Rate point to the same direction with small angle with each other. They are strongly positively correlated with each other. These components are also contributing to PC1. From the content perspective this is very logical. When girls are not educated - meaning families and the society are not investing in them - they are in higher risk to be married as children, and when they don’t have education, own income and status, their healthy needs are not seen important in the society.
The remaining variables show to the opposite direction. Those variables are Population with Secondary Education (Female), Expected Years of Education, Gross National Income (GNI) per Capita and Life Expectancy at Birth. They are positively correlated with each other and negatively correlated with maternal mortality ratio and adolescent birth rate. These components are also contributing negatively to PC1.
The correlation matrix confirms correlations.
cor_matrix<-round(cor(human2), digits=2)
cor_matrix
## Edu2.FM Labo.FM Edu.Exp Life.Exp GNI Mat.Mor Ado.Birth Parli.F
## Edu2.FM 1.00 0.01 0.59 0.58 0.43 -0.66 -0.53 0.08
## Labo.FM 0.01 1.00 0.05 -0.14 -0.02 0.24 0.12 0.25
## Edu.Exp 0.59 0.05 1.00 0.79 0.62 -0.74 -0.70 0.21
## Life.Exp 0.58 -0.14 0.79 1.00 0.63 -0.86 -0.73 0.17
## GNI 0.43 -0.02 0.62 0.63 1.00 -0.50 -0.56 0.09
## Mat.Mor -0.66 0.24 -0.74 -0.86 -0.50 1.00 0.76 -0.09
## Ado.Birth -0.53 0.12 -0.70 -0.73 -0.56 0.76 1.00 -0.07
## Parli.F 0.08 0.25 0.21 0.17 0.09 -0.09 -0.07 1.00
pca_human2
## Standard deviations (1, .., p=8):
## [1] 2.0708380 1.1397204 0.8750485 0.7788630 0.6619563 0.5363061 0.4589994
## [8] 0.3222406
##
## Rotation (n x k) = (8 x 8):
## PC1 PC2 PC3 PC4 PC5
## Edu2.FM -0.35664370 0.03796058 -0.24223089 0.62678110 -0.5983585
## Labo.FM 0.05457785 0.72432726 -0.58428770 0.06199424 0.2625067
## Edu.Exp -0.42766720 0.13940571 -0.07340270 -0.07020294 0.1659678
## Life.Exp -0.44372240 -0.02530473 0.10991305 -0.05834819 0.1628935
## GNI -0.35048295 0.05060876 -0.20168779 -0.72727675 -0.4950306
## Mat.Mor 0.43697098 0.14508727 -0.12522539 -0.25170614 -0.1800657
## Ado.Birth 0.41126010 0.07708468 0.01968243 0.04986763 -0.4672068
## Parli.F -0.08438558 0.65136866 0.72506309 0.01396293 -0.1523699
## PC6 PC7 PC8
## Edu2.FM 0.17713316 0.05773644 0.16459453
## Labo.FM -0.03500707 -0.22729927 -0.07304568
## Edu.Exp -0.38606919 0.77962966 -0.05415984
## Life.Exp -0.42242796 -0.43406432 0.62737008
## GNI 0.11120305 -0.13711838 -0.16961173
## Mat.Mor 0.17370039 0.35380306 0.72193946
## Ado.Birth -0.76056557 -0.06897064 -0.14335186
## Parli.F 0.13749772 0.00568387 -0.02306476
In PC1 the most meaningful components are life expectancy to one direction and maternal mortality to the other direction. As a whole, the meaningful components in PC1 are referring life expectancy as a whole. When a woman’s life is valued, she is educated, given opportunites, taken caren of at labour and thus she lives longer.
In PC2 Labour Force Participation Rate (Female) and Percent Female Representation in Parliament are the most meaningful components.These metrics could be grouped as “Women attendance rate in society”. PC1 explains 53,6 % and PC2 16,2%. In other words, factors related to the life excpectancy explain the most and factors related to women attendance rate in the society covers about 16 %. Next groupings are under 10 %.
The data used here is based on a questionnaire on tea. 300 individuals were asked how they drink tea (18 questions), what are their product’s perception (12 questions) and some personal details (4 questions).
The tea set data is loaded. There are 300 rows and 36 variables. Breakfast, tea time, evening, lunch, dinner, always, home, work, tearoom, friends, resto, pub, sugar, sex, escape, spirituality, healthy, diuretic, friendliness, iron, feminine, sophisticated, slimming, exciting, relaxing, effect on health and sport have two options (being binary), other variables have more. Only price and age are continous.
#install.packages("FactoMineR")
library(FactoMineR)
library(dplyr)
library(MASS)
library(tidyr)
library(stringr)
tea_time <-tea
summary(tea_time)
str(tea_time)
dim(tea_time)
str
keep_columns <- c("Tea", "How", "how", "sugar", "where", "lunch","where","price","lunch","friends","friendliness")
tea_time2 <- select(tea, keep_columns)
mca_tea <- MCA(tea_time2, graph = FALSE)
summary(mca_tea)
print(mca_tea)
summary
MCA graphs and factor map are created
mca_tea <- MCA(tea_time2, graph = TRUE)
plot(mca_tea, invisible=c("ind"))
Closer look to eigenvalues shows that the first MCA dimension covers almost 12% of variance and 6 dimensions reach over 50 %.
library(factoextra)
eig.val <- get_eigenvalue(mca_tea)
head(eig.val)
fviz_screeplot(mca_tea, addlabels = TRUE, ylim = c(0, 45))
Next I tried biplot drawing, where individuals are in blue and variables in red. But this was too wild to make any real analysis. The distance between any row points or column points should give a measure of their similarity (or dissimilarity). Row points with similar profile are close on the factor map. The same holds true for column points. But anyway, one can see that for instance individuals 212 and 199 are very similar.
fviz_mca_biplot(mca_tea,
repel = TRUE, # Avoid text overlapping (slow if many point)
ggtheme = theme_minimal())
The next plots identifies variables that are the most correlated with each dimension. The squared correlations between variables and the dimensions are used as coordinates. Where, how and price are most correlated with the dimansion 1 and friends and tea with dimension 2. Sugar is not actually correlating with either dimension.
fviz_mca_var(mca_tea, choice = "mca.cor",
repel = TRUE, # Avoid text overlapping (slow)
ggtheme = theme_minimal())
Here similar variable categories are grouped toghether. Negative correlation is in opposite directions; for instance, p_private label and chain stroe+tea shop are negatively correlated
fviz_mca_var(mca_tea, col.var="black", shape.var = 15,
repel = TRUE)
In the end I analyse, which top 20 variable categories contributes most to dimensions 1 and 2. Tea shop is contributing the second most in both dimensions. P_upscale is contributing over 15 % in dimension 1 and chainstore+tea shop abou 11 % in dimension 2.
fviz_contrib(mca_tea, choice = "var", axes = 1, top = 20)
fviz_contrib(mca_tea, choice = "var", axes = 2, top = 20)
***
Work summary Codes are available at
The data is based on th brief psychiatric rating scale (BPRS) measured before treatment began (week 0) and then at weekly intervals for eight weeks. The BPRS assesses the level of 18 symptom constructs such as hostility, suspiciousness, hallucinations and grandiosity; each of these is rated from one (not present) to seven (extremely severe). The scale is used to evaluate patients suspected of having schizophrenia.
Treatment variable is either 1 or 2 and it tells which was the taken treatment. Subject refers to patient ids and week to the measurement week. Minimum points are 0, maximum 18*7=126. Ratings are done during 9 weeks and for each patient both treatments are done.
Teh data is first loaded in a wide form. The basic checks show 40 rows and 11 variables. Weeks are rows in the data. In the wide data format there is a single row for every data point with multiple columns to hold the values of various attributes.
BPRS <- read.table("https://raw.githubusercontent.com/KimmoVehkalahti/MABS/master/Examples/data/BPRS.txt", sep =" ", header = T)
names(BPRS)
## [1] "treatment" "subject" "week0" "week1" "week2"
## [6] "week3" "week4" "week5" "week6" "week7"
## [11] "week8"
str(BPRS)
## 'data.frame': 40 obs. of 11 variables:
## $ treatment: int 1 1 1 1 1 1 1 1 1 1 ...
## $ subject : int 1 2 3 4 5 6 7 8 9 10 ...
## $ week0 : int 42 58 54 55 72 48 71 30 41 57 ...
## $ week1 : int 36 68 55 77 75 43 61 36 43 51 ...
## $ week2 : int 36 61 41 49 72 41 47 38 39 51 ...
## $ week3 : int 43 55 38 54 65 38 30 38 35 55 ...
## $ week4 : int 41 43 43 56 50 36 27 31 28 53 ...
## $ week5 : int 40 34 28 50 39 29 40 26 22 43 ...
## $ week6 : int 38 28 29 47 32 33 30 26 20 43 ...
## $ week7 : int 47 28 25 42 38 27 31 25 23 39 ...
## $ week8 : int 51 28 24 46 32 25 31 24 21 32 ...
summary(BPRS)
## treatment subject week0 week1
## Min. :1.0 Min. : 1.00 Min. :24.00 Min. :23.00
## 1st Qu.:1.0 1st Qu.: 5.75 1st Qu.:38.00 1st Qu.:35.00
## Median :1.5 Median :10.50 Median :46.00 Median :41.00
## Mean :1.5 Mean :10.50 Mean :48.00 Mean :46.33
## 3rd Qu.:2.0 3rd Qu.:15.25 3rd Qu.:58.25 3rd Qu.:54.25
## Max. :2.0 Max. :20.00 Max. :78.00 Max. :95.00
## week2 week3 week4 week5
## Min. :26.0 Min. :24.00 Min. :20.00 Min. :20.00
## 1st Qu.:32.0 1st Qu.:29.75 1st Qu.:28.00 1st Qu.:26.00
## Median :38.0 Median :36.50 Median :34.50 Median :30.50
## Mean :41.7 Mean :39.15 Mean :36.35 Mean :32.55
## 3rd Qu.:49.0 3rd Qu.:44.50 3rd Qu.:43.00 3rd Qu.:38.00
## Max. :75.0 Max. :76.00 Max. :66.00 Max. :64.00
## week6 week7 week8
## Min. :19.00 Min. :18.0 Min. :20.00
## 1st Qu.:22.75 1st Qu.:23.0 1st Qu.:22.75
## Median :28.50 Median :30.0 Median :28.00
## Mean :31.23 Mean :32.2 Mean :31.43
## 3rd Qu.:37.00 3rd Qu.:38.0 3rd Qu.:35.25
## Max. :64.00 Max. :62.0 Max. :75.00
head(BPRS)
## treatment subject week0 week1 week2 week3 week4 week5 week6 week7 week8
## 1 1 1 42 36 36 43 41 40 38 47 51
## 2 1 2 58 68 61 55 43 34 28 28 28
## 3 1 3 54 55 41 38 43 28 29 25 24
## 4 1 4 55 77 49 54 56 50 47 42 46
## 5 1 5 72 75 72 65 50 39 32 38 32
## 6 1 6 48 43 41 38 36 29 33 27 25
The similar steps are taken with the RATS data. The RATS data is collected in a nutrition study conducted in three groups of rats. The groups were put on different diets, and each animal’s body weight (grams) was recorded repeatedly (approximately) weekly, except in week seven when two recordings were taken) over a 9-week period. The question of most interest is whether the growth profiles of the three groups differ.
From the head & summary of the data it is easy to observe that data is in wide format, in other words there is again a single row for every data point with multiple columns to hold the values of various attributes.
RATS <- read.table("https://raw.githubusercontent.com/KimmoVehkalahti/MABS/master/Examples/data/rats.txt", header = TRUE, sep = '\t')
names(RATS)
## [1] "ID" "Group" "WD1" "WD8" "WD15" "WD22" "WD29" "WD36"
## [9] "WD43" "WD44" "WD50" "WD57" "WD64"
str(RATS)
## 'data.frame': 16 obs. of 13 variables:
## $ ID : int 1 2 3 4 5 6 7 8 9 10 ...
## $ Group: int 1 1 1 1 1 1 1 1 2 2 ...
## $ WD1 : int 240 225 245 260 255 260 275 245 410 405 ...
## $ WD8 : int 250 230 250 255 260 265 275 255 415 420 ...
## $ WD15 : int 255 230 250 255 255 270 260 260 425 430 ...
## $ WD22 : int 260 232 255 265 270 275 270 268 428 440 ...
## $ WD29 : int 262 240 262 265 270 275 273 270 438 448 ...
## $ WD36 : int 258 240 265 268 273 277 274 265 443 460 ...
## $ WD43 : int 266 243 267 270 274 278 276 265 442 458 ...
## $ WD44 : int 266 244 267 272 273 278 271 267 446 464 ...
## $ WD50 : int 265 238 264 274 276 284 282 273 456 475 ...
## $ WD57 : int 272 247 268 273 278 279 281 274 468 484 ...
## $ WD64 : int 278 245 269 275 280 281 284 278 478 496 ...
summary(RATS)
## ID Group WD1 WD8
## Min. : 1.00 Min. :1.00 Min. :225.0 Min. :230.0
## 1st Qu.: 4.75 1st Qu.:1.00 1st Qu.:252.5 1st Qu.:255.0
## Median : 8.50 Median :1.50 Median :340.0 Median :345.0
## Mean : 8.50 Mean :1.75 Mean :365.9 Mean :369.1
## 3rd Qu.:12.25 3rd Qu.:2.25 3rd Qu.:480.0 3rd Qu.:476.2
## Max. :16.00 Max. :3.00 Max. :555.0 Max. :560.0
## WD15 WD22 WD29 WD36
## Min. :230.0 Min. :232.0 Min. :240.0 Min. :240.0
## 1st Qu.:255.0 1st Qu.:267.2 1st Qu.:268.8 1st Qu.:267.2
## Median :347.5 Median :351.5 Median :356.5 Median :360.0
## Mean :372.5 Mean :379.2 Mean :383.9 Mean :387.0
## 3rd Qu.:486.2 3rd Qu.:492.5 3rd Qu.:497.8 3rd Qu.:504.2
## Max. :565.0 Max. :580.0 Max. :590.0 Max. :597.0
## WD43 WD44 WD50 WD57
## Min. :243.0 Min. :244.0 Min. :238.0 Min. :247.0
## 1st Qu.:269.2 1st Qu.:270.0 1st Qu.:273.8 1st Qu.:273.8
## Median :360.0 Median :362.0 Median :370.0 Median :373.5
## Mean :386.0 Mean :388.3 Mean :394.6 Mean :398.6
## 3rd Qu.:501.0 3rd Qu.:510.5 3rd Qu.:516.0 3rd Qu.:524.5
## Max. :595.0 Max. :595.0 Max. :612.0 Max. :618.0
## WD64
## Min. :245.0
## 1st Qu.:278.0
## Median :378.0
## Mean :404.1
## 3rd Qu.:530.8
## Max. :628.0
head(RATS)
## ID Group WD1 WD8 WD15 WD22 WD29 WD36 WD43 WD44 WD50 WD57 WD64
## 1 1 1 240 250 255 260 262 258 266 266 265 272 278
## 2 2 1 225 230 230 232 240 240 243 244 238 247 245
## 3 3 1 245 250 250 255 262 265 267 267 264 268 269
## 4 4 1 260 255 255 265 265 268 270 272 274 273 275
## 5 5 1 255 260 255 270 270 273 274 273 276 278 280
## 6 6 1 260 265 270 275 275 277 278 278 284 279 281
In BPRS, categorical datasets are created and week variable is created to show the week numbers
library(dplyr)
library(tidyr)
BPRS$treatment <- factor(BPRS$treatment)
BPRS$subject <- factor(BPRS$subject)
# Convert to long form
BPRSL <- BPRS %>% gather(key = weeks, value = bprs, -treatment, -subject)
# Extract the week number
BPRSL <- BPRSL %>% mutate(week = as.integer(substr(weeks,5,5)))
# glimpse at the BPRSL data
glimpse(BPRSL)
## Observations: 360
## Variables: 5
## $ treatment <fct> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
## $ subject <fct> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 1...
## $ weeks <chr> "week0", "week0", "week0", "week0", "week0", "week0"...
## $ bprs <int> 42, 58, 54, 55, 72, 48, 71, 30, 41, 57, 30, 55, 36, ...
## $ week <int> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
dim(BPRSL)
## [1] 360 5
str(BPRSL)
## 'data.frame': 360 obs. of 5 variables:
## $ treatment: Factor w/ 2 levels "1","2": 1 1 1 1 1 1 1 1 1 1 ...
## $ subject : Factor w/ 20 levels "1","2","3","4",..: 1 2 3 4 5 6 7 8 9 10 ...
## $ weeks : chr "week0" "week0" "week0" "week0" ...
## $ bprs : int 42 58 54 55 72 48 71 30 41 57 ...
## $ week : int 0 0 0 0 0 0 0 0 0 0 ...
Now BPRS data is in the long format. In the long format, for each data point, there are as many rows as the number of attributes and each row contains the value of a particular attribute for a given data point.
In RATS, categorical datasets are created and Time variable is created to show the week numbers. The similar change from wide format to long format is visible. There are now 5 variables and 176 observations. In the wide format, there were 16 rows and 13 columns. The weeknumbers are now attribute for the data point.
RATS$ID <- factor(RATS$ID)
RATS$Group <- factor(RATS$Group)
# Convert data to long form
RATSL <- RATS %>%
gather(key = WD, value = Weight, -ID, -Group) %>%
mutate(Time = as.integer(substr(WD,3,4)))
# Glimpse the data
glimpse(RATSL)
## Observations: 176
## Variables: 5
## $ ID <fct> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, ...
## $ Group <fct> 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 1, 1, 1...
## $ WD <chr> "WD1", "WD1", "WD1", "WD1", "WD1", "WD1", "WD1", "WD1",...
## $ Weight <int> 240, 225, 245, 260, 255, 260, 275, 245, 410, 405, 445, ...
## $ Time <int> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 8, 8, 8...
dim(RATSL)
## [1] 176 5
str(RATSL)
## 'data.frame': 176 obs. of 5 variables:
## $ ID : Factor w/ 16 levels "1","2","3","4",..: 1 2 3 4 5 6 7 8 9 10 ...
## $ Group : Factor w/ 3 levels "1","2","3": 1 1 1 1 1 1 1 1 2 2 ...
## $ WD : chr "WD1" "WD1" "WD1" "WD1" ...
## $ Weight: int 240 225 245 260 255 260 275 245 410 405 ...
## $ Time : int 1 1 1 1 1 1 1 1 1 1 ...
head(RATSL)
## ID Group WD Weight Time
## 1 1 1 WD1 240 1
## 2 2 1 WD1 225 1
## 3 3 1 WD1 245 1
## 4 4 1 WD1 260 1
## 5 5 1 WD1 255 1
## 6 6 1 WD1 260 1
The object of the analysis is to use linear mixed effects models to BPRSL data. First it adviced to join points belonging to each patient and draw a plot to see, are individual measure points independent.
library(ggplot2)
ggplot(BPRSL, aes(x = week, y = bprs, linetype = subject)) +
geom_line() +
scale_linetype_manual(values = rep(1:10, times=4)) +
facet_grid(. ~ treatment, labeller = label_both) +
theme(legend.position = "right") +
scale_y_continuous(limits = c(min(BPRSL$bprs), max(BPRSL$bprs)))
Individuals, who have high values in the beginning, tend to have higher values also at the end. Therefore I standardize the points to be able to see more clearly tracking by treatment. In standardization, the mean is 0. Now the plots are different, and it is not obvious, whether the treatment decreases the points compared to the starting time.
library(dplyr)
library(tidyr)
library(ggplot2)
BPRSL <- BPRSL %>%
group_by(week) %>%
mutate(stdbprs = (bprs - mean(bprs))/sd(bprs) ) %>%
ungroup()
ggplot(BPRSL, aes(x = week, y = stdbprs, linetype = subject)) +
geom_line() +
scale_linetype_manual(values = rep(1:10, times=4)) +
facet_grid(. ~ treatment, labeller = label_both) +
scale_y_continuous(name = "standardized bprs")
The explanatory variables are treatment and week.
Simple linear model is created for comparison. Multiple R-squares is 0.1851, P value is significat for the week. This is not valid modelling, because it assumes independence of the repeated measures of bprs - but this is not likely.
simple_linear_model <- lm(bprs ~ treatment + week, data = BPRSL)
summary(simple_linear_model)
##
## Call:
## lm(formula = bprs ~ treatment + week, data = BPRSL)
##
## Residuals:
## Min 1Q Median 3Q Max
## -22.454 -8.965 -3.196 7.002 50.244
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 46.4539 1.3670 33.982 <2e-16 ***
## treatment2 0.5722 1.3034 0.439 0.661
## week -2.2704 0.2524 -8.995 <2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 12.37 on 357 degrees of freedom
## Multiple R-squared: 0.1851, Adjusted R-squared: 0.1806
## F-statistic: 40.55 on 2 and 357 DF, p-value: < 2.2e-16
Random Intercept Model is created first. The standard deviation of a subject is 6.89, which is quite high and indicates that the values are spreading. The closer T is to 0, the more likely there isn’t a significant difference. Week’s t-value is high and it indicates relation, but treatment2 is close to zero - seems that it does not have effect on bprs resutls.
library(lme4)
BPRSL_ref <- lmer(bprs ~ week + treatment + (1 | subject), data = BPRSL, REML = FALSE)
summary(BPRSL_ref)
## Linear mixed model fit by maximum likelihood ['lmerMod']
## Formula: bprs ~ week + treatment + (1 | subject)
## Data: BPRSL
##
## AIC BIC logLik deviance df.resid
## 2748.7 2768.1 -1369.4 2738.7 355
##
## Scaled residuals:
## Min 1Q Median 3Q Max
## -3.0481 -0.6749 -0.1361 0.4813 3.4855
##
## Random effects:
## Groups Name Variance Std.Dev.
## subject (Intercept) 47.41 6.885
## Residual 104.21 10.208
## Number of obs: 360, groups: subject, 20
##
## Fixed effects:
## Estimate Std. Error t value
## (Intercept) 46.4539 1.9090 24.334
## week -2.2704 0.2084 -10.896
## treatment2 0.5722 1.0761 0.532
##
## Correlation of Fixed Effects:
## (Intr) week
## week -0.437
## treatment2 -0.282 0.000
Next Random Intercept and Random Slope Model is created. This model takes into account individual differences in bprs profiles but also the effect of weeks. Subject’s standard deviation is bigger than in Random Intercept Model. The closer T is to 0, the more likely there isn’t a significant difference. Week’s t-value is high and it indicates relation, but treatment2 is close to zero - seems that it does not have effect on bprs resutls.
BPRSL_ref1 <- lmer(bprs ~ week + treatment + (week | subject), data = BPRSL, REML = FALSE)
summary(BPRSL_ref1)
## Linear mixed model fit by maximum likelihood ['lmerMod']
## Formula: bprs ~ week + treatment + (week | subject)
## Data: BPRSL
##
## AIC BIC logLik deviance df.resid
## 2745.4 2772.6 -1365.7 2731.4 353
##
## Scaled residuals:
## Min 1Q Median 3Q Max
## -2.8919 -0.6194 -0.0691 0.5531 3.7977
##
## Random effects:
## Groups Name Variance Std.Dev. Corr
## subject (Intercept) 64.8222 8.0512
## week 0.9609 0.9803 -0.51
## Residual 97.4304 9.8707
## Number of obs: 360, groups: subject, 20
##
## Fixed effects:
## Estimate Std. Error t value
## (Intercept) 46.4539 2.1052 22.066
## week -2.2704 0.2977 -7.626
## treatment2 0.5722 1.0405 0.550
##
## Correlation of Fixed Effects:
## (Intr) week
## week -0.582
## treatment2 -0.247 0.000
# perform an ANOVA test on the two models
anova(BPRSL_ref1, BPRSL_ref)
## Data: BPRSL
## Models:
## BPRSL_ref: bprs ~ week + treatment + (1 | subject)
## BPRSL_ref1: bprs ~ week + treatment + (week | subject)
## Df AIC BIC logLik deviance Chisq Chi Df Pr(>Chisq)
## BPRSL_ref 5 2748.7 2768.1 -1369.4 2738.7
## BPRSL_ref1 7 2745.4 2772.6 -1365.7 2731.4 7.2721 2 0.02636 *
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
When models BPRSL_ref and BPRSL_ref1 are compared in the likelihood ratio test above, chi square value is close to zero, and it is significat on 0.05 level. Chi square tests random effects variance and it indicates here that the model is catching the random effects. The lower the value the better the fit against the comparison model.
BPRSL_ref2 <- lmer(bprs ~ week * treatment + (week | subject), data = BPRSL, REML = FALSE)
summary(BPRSL_ref2)
## Linear mixed model fit by maximum likelihood ['lmerMod']
## Formula: bprs ~ week * treatment + (week | subject)
## Data: BPRSL
##
## AIC BIC logLik deviance df.resid
## 2744.3 2775.4 -1364.1 2728.3 352
##
## Scaled residuals:
## Min 1Q Median 3Q Max
## -3.0512 -0.6271 -0.0768 0.5288 3.9260
##
## Random effects:
## Groups Name Variance Std.Dev. Corr
## subject (Intercept) 64.9964 8.0620
## week 0.9687 0.9842 -0.51
## Residual 96.4707 9.8220
## Number of obs: 360, groups: subject, 20
##
## Fixed effects:
## Estimate Std. Error t value
## (Intercept) 47.8856 2.2521 21.262
## week -2.6283 0.3589 -7.323
## treatment2 -2.2911 1.9090 -1.200
## week:treatment2 0.7158 0.4010 1.785
##
## Correlation of Fixed Effects:
## (Intr) week trtmn2
## week -0.650
## treatment2 -0.424 0.469
## wek:trtmnt2 0.356 -0.559 -0.840
anova(BPRSL_ref2, BPRSL_ref1)
## Data: BPRSL
## Models:
## BPRSL_ref1: bprs ~ week + treatment + (week | subject)
## BPRSL_ref2: bprs ~ week * treatment + (week | subject)
## Df AIC BIC logLik deviance Chisq Chi Df Pr(>Chisq)
## BPRSL_ref1 7 2745.4 2772.6 -1365.7 2731.4
## BPRSL_ref2 8 2744.3 2775.4 -1364.1 2728.3 3.1712 1 0.07495 .
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
A vector of fitted values is created and added to the BPRSL data
Fitted <- fitted(BPRSL_ref2)
BPRSL <- BPRSL %>%
mutate(Fitted)
Next fitted values from the model are plotted. The both treatments show decrease of bprs points over time.
ggplot(BPRSL, aes(x = week, y = Fitted, group= subject, linetype = treatment)) +
geom_line() +
scale_linetype_manual(values = rep(1:10, times=4)) +
facet_grid(. ~ treatment, labeller = label_both) +
theme(legend.position = "right") +
scale_y_continuous(limits = c(min(BPRSL$bprs), max(BPRSL$bprs)))
Comparison to observed values:
ggplot(BPRSL, aes(x = week, y = bprs, group= subject, linetype = treatment)) +
geom_line() +
scale_linetype_manual(values = rep(1:10, times=4)) +
facet_grid(. ~ treatment, labeller = label_both) +
theme(legend.position = "right") +
scale_y_continuous(limits = c(min(BPRSL$bprs), max(BPRSL$bprs)))
The weight development of each mouse is shown in figures below.
ggplot(RATSL, aes(x = Time, y = Weight, linetype = ID)) +
geom_line() +
scale_linetype_manual(values = rep(1:10, times=4)) +
facet_grid(. ~ Group, labeller = label_both) +
theme(legend.position = "right") +
scale_y_continuous(limits = c(min(RATSL$Weight), max(RATSL$Weight)))
Individuals, who have high values in the beginning, tend to have higher values also at the end, similary as in BPRS data. Therefore I standardize the weights to be able to see more clearly tracking by groups. In standardization, the mean is 0.
RATSL <- RATSL %>%
group_by(Time) %>%
mutate(stdweight = (Weight - mean(Weight))/sd(Weight) ) %>%
ungroup()
glimpse(RATSL)
## Observations: 176
## Variables: 6
## $ ID <fct> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 1...
## $ Group <fct> 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 1, 1...
## $ WD <chr> "WD1", "WD1", "WD1", "WD1", "WD1", "WD1", "WD1", "WD...
## $ Weight <int> 240, 225, 245, 260, 255, 260, 275, 245, 410, 405, 44...
## $ Time <int> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 8, 8...
## $ stdweight <dbl> -1.0011429, -1.1203857, -0.9613953, -0.8421525, -0.8...
ggplot(RATSL, aes(x = Time, y = stdweight, linetype = ID)) +
geom_line() +
scale_linetype_manual(values = rep(1:10, times=4)) +
facet_grid(. ~ Group, labeller = label_both) +
scale_y_continuous(name = "standardized weights")
Standard error of the mean is calculated next.
n <- RATSL$Time %>% unique() %>% length()
RATSSS <- RATSL %>%
group_by(Group, Time) %>%
summarise( mean = mean(Weight), se = sd(Weight)/sqrt(n) ) %>%
ungroup()
RATSSS$se
## [1] 4.589478 3.947710 3.460116 4.100800 3.333956 3.552939 3.302646
## [8] 3.073768 4.390071 3.243375 3.751190 21.047385 20.486507 19.866982
## [15] 21.311542 21.660430 21.865117 21.898526 21.483433 22.389628 22.044033
## [22] 22.224066 8.382431 8.561276 7.917663 7.399324 7.561365 7.358257
## [29] 6.210329 5.548683 6.407264 5.131601 5.696224
glimpse(RATSSS)
## Observations: 33
## Variables: 4
## $ Group <fct> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2,...
## $ Time <int> 1, 8, 15, 22, 29, 36, 43, 44, 50, 57, 64, 1, 8, 15, 22, ...
## $ mean <dbl> 250.625, 255.000, 254.375, 261.875, 264.625, 265.000, 26...
## $ se <dbl> 4.589478, 3.947710, 3.460116, 4.100800, 3.333956, 3.5529...
Mean weight grow profiles are drawn in the next figure. All groups gain wieght, but groups 2 and 3 gain it faster than group 1. Group 2 seems to grow th most, but there are also more variance in it compared to other groups.
ggplot(RATSSS, aes(x = Time, y = mean, linetype = Group, shape = Group)) +
geom_line() +
scale_linetype_manual(values = c(1,2,3)) +
geom_point(size=3) +
scale_shape_manual(values = c(1,2,3)) +
geom_errorbar(aes(ymin = mean - se, ymax = mean + se, linetype="1"), width=0.3) +
theme(legend.position = "right") +
scale_y_continuous(name = "mean(Weight) +/- se(Weight)")
Means from weeks 8-64 are calculate to check the mean development. The first week (week 1) is left out because it was the starting week and there was not yet any change due to nutrition changes.
RATSSL8S <- RATSL %>%
filter(Time > 1) %>%
group_by(Group, ID) %>%
summarise( mean=mean(Weight))
# Glimpse the data
glimpse(RATSSL8S)
## Observations: 16
## Variables: 3
## Groups: Group [3]
## $ Group <fct> 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3
## $ ID <fct> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16
## $ mean <dbl> 263.2, 238.9, 261.7, 267.2, 270.9, 276.2, 274.6, 267.5, ...
ggplot(RATSSL8S, aes(x = Group, y = mean)) +
geom_boxplot() +
stat_summary(fun.y = "mean", geom = "point", shape=23, size=4, fill = "white") +
scale_y_continuous(name = "mean(Weight), weeks 8-64")
There are some outliers in data. Next the outliers are taken away based on the picture above. Both more than 550 and under 250 outliers are excluded.
RATSSL8S1 <- RATSSL8S %>%
filter(mean < 550 & mean>250)
ggplot(RATSSL8S1, aes(x = Group, y = mean)) +
geom_boxplot() +
stat_summary(fun.y = "mean", geom = "point", shape=23, size=4, fill = "white") +
scale_y_continuous(name = "mean(Weight), weeks 8-64")
T-test cannot be run because there are more than two groups. Anova is used instead.
# Add the baseline from the original data as a new variable to the summary data
RATSSL8S2 <- RATSSL8S %>%
mutate(baseline = RATS$Time1)
# Fit the linear model with the mean as the response
fit <- lm(mean ~ Group, data = RATSSL8S2)
# Compute the analysis of variance table for the fitted model with anova()
anova(fit)
## Analysis of Variance Table
##
## Response: mean
## Df Sum Sq Mean Sq F value Pr(>F)
## Group 2 238620 119310 88.525 2.679e-08 ***
## Residuals 13 17521 1348
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
confint(fit)
## 2.5 % 97.5 %
## (Intercept) 236.9843 293.0657
## Group2 174.2071 271.3429
## Group3 213.9071 311.0429
P value is very low, under 0.05 meaning there is a significant relationship between group and weight. F value is high, which also is good. Confidence intervals for group 2 and group 3 are also shown. So in the end, nutrition group is very meaningful.